snapchatdotcom snapchatdotcom - 6 months ago 27
Swift Question

Calling a function that has a TypeAlias as a parameter?

So I've written a little practice program that has to do with closures. I'm trying to better understand how the asynchronous concept works. When I try to call

request()
, I get conversion errors as seen below:

import UIKit

let correctPasscode = "3EyX"

typealias CompletionHandler = (result: AnyObject?, error: String?) -> Void

func request(passcode: String, completionHandler: CompletionHandler) {

sendBackRequest(passcode) {(result, error) -> Void in
if error != nil {
print(error)
}
else {
print(result)

}}

}

func sendBackRequest(passCode: String, completionHandler: CompletionHandler) {
if passCode == correctPasscode {
completionHandler(result: "Correct. Please proceed", error: nil)

} else {
completionHandler(result: nil, error: "There was an error signing in")

}
}


request(correctPasscode, completionHandler: CompletionHandler) // Error happens here


enter image description here

Answer

Type alias is there to tell you what actual type you need to pass. In this case, the type is a closure of type

(result: AnyObject?, error: String?) -> Void

You pass it like this:

request(correctPasscode, completionHandler:{
    (result: AnyObject?, error: String?) in 
    print("Inside the handler...")
    // Do some useful things here
})

or even shorter -

request(correctPasscode) {
    (result: AnyObject?, error: String?) in 
    print("Inside the handler...")
    // Do some useful things here
}

or even shorter - (the types are known via the func declaration) -

request(correctPasscode) { result, error in
    print("Inside the handler...")
    // Do some useful things here
}