Completion handlers in Swift

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:

1
2
3
func doSomething(flag:Bool, completionHandler:(success:Bool) -> Void) {
completionHandler(success:true)
}

and call the function:

1
2
3
4
5
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.

1
typealias FooCompletionHandler = (obj:AnyObject?, success:Bool?) -> Void

which can be used in a function definition:

1
2
3
func useAliasHandler(completionHandler:FooCompletionHandler) {
completionHandler(obj:nil, success:true)
}

and called in this fashion:

1
2
3
f.useAliasHandler({(obj:AnyObject?, success:Bool?) -> Void in
println("hi")
})

It appears that you still must supply the closure arguments in the function call. I could be wrong.

Here are all of my noodlings with closures:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import Foundation

// 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
  • Notes from Coding in Swift, Tal Bereznitskey Link
  • Swift Functions and Closures, Andrew Carter Link