ios - Closures in Swift, blocks in Objective-C: their usefulness and when to use -


i've found objective-c socketio library , trying implement in first swift app. here's code i'm trying port:

__weak typeof(self) weakself = self; self.socket.onconnect = ^() {     weakself.socketisconnected = yes;     [weakself mapview: weakself.mapview didupdateuserlocation: weakself.mapview.userlocation]; }; 

from limited understanding ^() {} block in objective c. i've looked , closures seem loose equivalent swift. first obvious question how same result in swift?

i've tried following error fatal error: unexpectedly found nil while unwrapping optional value (lldb):

self.socket.onconnect = { () -> void in     println("connected!") } 

also, behind scenes what's happening here? asynchronous callback function seem appropriate wasn't used , i'd understand why.

update

as pointed out @jtbandes, socket in fact nil code running outside of connection callback (i know, silly mistake). solution first question:

siosocket.socketwithhost(server) { (socket: siosocket!) in     self.socket = socket      self.socket.onconnect = { () -> void in         println("connected!")     } } 

objective-c blocks , swift closures more loose equivalents. direct equivalents.

a block/closure anonymous function inherits it's enclosing scope.

i'm still working in objective-c, i'm used terminology. i'll use terms

blocks useful in lots of ways.

completion code 1 example.

without blocks, if you're setting async networking class, might give delegate property, , define protocol callbacks class uses notify it's delegate events download complete, errors, etc.

this makes lot of message handling infrastructure in lots of different places. have define protocol. have add delegate property networking class. have implement set of delegate messages in client class. may have pass context information callbacks, etc.

with blocks, invoke method asks networking service, , provide completion block. when service complete, invokes provided code block. might add parameters completion block pointer data, success boolean, or whatever appropriate. code block can have access variables defined in enclosing scope, can helpful.

you can save blocks collections, can use blocks in sort methods, , int lots of other cases.

the code posted sets block property on object in question, self.socket. looks block of code gets called after socket connection established.

there direct equivalents in swift. i've poked around in swift however, i'll leave others translation.

i suggest browsing through apple's classes ideas on how use blocks. take @ nsurlconnection , nsurlsession if you're interested in async networking. take @ block-based view animation methods take animation block , completion block. give idea of ways can use blocks handling async events, or passing code class work done.

another interesting use of blocks in handling collections arrays. there methods take nscomparator block , sort array, , there methods enumerate through array, performing block of code on each element and/or selecting subset of elements , returning index set of array indexes.

duncan


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -