When executing a concurrent operation, we often use completion handlers to execute a code block on completion. In Swift, closures are the way to accomplish that task.
Declaring a function with a completion handler
In the function definition, we can fully declare the closure:
var f = Foo() // flag parameter name is optional here f.doSomething(false, completionHandler:{(success:Bool) -> Void in println("value = \(success)") })
Using typealias
In Objective-C we’d use a typedef for a block to simplify the method declaration that uses it. We can use typealias in Swift to do the same thing.
// in ObjC we would define a block with typedef // in swift it's typealias with a closure typealias FooCompletionHandler = (obj:AnyObject?, success:Bool?) -> Void
class Foo { // function with a completion handler func doSomething(flag:Bool, completionHandler:(success:Bool) -> Void) { completionHandler(success:true) }
// function with a typealias'd completionHandler func useAliasHandler(completionHandler:FooCompletionHandler) { completionHandler(obj:nil, success:true) }
/* try another return type in block */ func doSomethingElse(completionHandler:(data:String) -> Void) { var chars:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" chars += chars.lowercaseString var s = "" for i:Int in 1...10 { let r:UInt32 = arc4random() % UInt32(countElements(chars)) let index = advance(chars.startIndex, Int(r)) let char:Character = chars[index] s = s + char } completionHandler(data:s) } }
var f = Foo() // completionHandler parameter name is optional here f.doSomething(false, completionHandler:{(success:Bool) -> Void in println("value = \(success)") })
// completionHandler parameter name may not be used here f.doSomethingElse( {(data:String) -> Void in println("data = \(data)") })
References
Swift - Creating Methods with Closures, Michael Kral Link