Callback function syntax in Swift

You've declared callback to take no arguments, and then you're trying to pass it an argument.

You specified type (()->(String))?, which is an optional function that takes no arguments and returns a String.

Perhaps you mean to specify ((String)->())?, which is an optional function that takes a String and returns nothing.


I use this way :

ViewController1

destination.callback = { (id) -> Void in
            print("callback")
            print(id)
        }

ViewController2

var callback: ((_ id: Int) -> Void)?
callback?(example_id)

Rob's answer is correct, though I'd like to share an example of a simple working callback / completion handler, you can download an example project below and experiment with the getBoolValue's input.

Swift 5:

func getBoolValue(number : Int, completion: (Bool)->()) {
    if number > 5 {
        completion(true)
    } else {
        completion(false)
    }
}

getBoolValue(number: 2) { (result) -> () in
    // do stuff with the result
    print(result)
}

Important to understand:

(String)->() // takes a String returns void
()->(String) // takes void returns a String

try below code updated for Swift 3

func getBoolValue(number : Int, completion: (Bool)->()) {
    if number > 5 {
        completion(true)
    } else {
        completion(false)
    }
}

getBoolValue(number : 8, completion:{ result in
    print(result)
})