http://artsy.github.io/blog/2016/06/24/typealias-for-great-good/
Type aliases allow developers to define synonyms for pre-existing types.
You can use typealias for most any type: classes, enums, structs, tuples, closures, etc.
Here are a few examples:
1 2 3 4 |
typealias Name = String typealias Employees = Array<Employee> typealias GridPoint = (Int, Int) typealias CompletionHandler = (ErrorType?) -> Void |
Defining the handler type
1 |
typealias CompletionHandler = (Bool) -> Void |
Basically, we want to declare a completion handler that takes in bool as parameter, returns void
Defining the function, and its interface
Declare the function definition. It takes two parameters, url and a handler type, which we declared.
The closure type we declared is CompletionHandler. So we say, the completionHandler takes in closure type called CompletionHandler. It takes in one parameter of bool type, and returns void.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
func downloadFileFromURL(url:NSURL, completionHandler: CompletionHandler) { print("--> \(#function)") print("\(#function) - accessing \(url.absoluteURL) ") print("\(#function) - complete!, let's handle the completion") //calls the completion handler completionHandler(true) print("<-- \(#function)") } |
As you can see, we call this closure within the code of our function.
Using the function, defining the closure
Now we use and call the function. At the same time, we define the closure, and pass it in.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//use it downloadFileFromURL(url: NSURL(string: "www.google.com")!, completionHandler: { //declare handler paramters here (success) -> Void in print("--> \(#function) - calling completion handler") if(success) { print("success!") } else { print("failed!") } print("<-- \(#function)") }) |
1 2 3 4 5 6 7 8 9 |
output: MutatingEx --> downloadFileFromURL(url:completionHandler:) start downloadFileFromURL(url:completionHandler:) - accessing Optional(www.google.com) downloadFileFromURL(url:completionHandler:) - complete!, let's handle the completion --> MutatingEx - calling completion handle success! <-- MutatingEx - completion handler finished <-- downloadFileFromURL(url:completionHandler:) end |
Ex – adding two strings together, returning result
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
typealias CompletionHandler2 = (String, String) -> String func test(completionHandler: CompletionHandler2) -> String { return completionHandler("h3h3","haha") } let result = test(completionHandler: { (firstWord, secondWord) -> String in print("firstWord - \(firstWord)") print("secondWord - \(firstWord)") return String(stringLiteral: firstWord + secondWord) }) print("\(result)") |