user3674231
user3674231

Reputation:

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

Upvotes: 1

Views: 1066

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

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
}

Upvotes: 3

hnh
hnh

Reputation: 14805

I'm not sure what you try to accomplish, but this line:

request(correctPasscode, completionHandler: CompletionHandler)

doesn't compile because you are not passing a CompletionHandler closure to the function but rather a type object representing the type of that completion handler.

Hence the error: Cannot convert value of 'CompletionHandler.*Type*'.

A valid call would be:

request(correctPasscode) { result, error in
  print("result was \(result), and error was \(error)")
}

But then your request function doesn't do anything with the closure which is passed in. It is a little hard to say what you want ...

Upvotes: 1

Related Questions