Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

ios - Callback function syntax in Swift

I am attempting pass a function to another function and then have the passed function executed passing to it a variable.

Here is my code:

func showStandardPrompt(prompt:String,view: UIViewController,numberInput: Bool, callback: (()->(String))?) {
    let alert = UIAlertController(title: "Input Data", message: prompt, preferredStyle: .Alert)
    alert.addTextFieldWithConfigurationHandler { (textField) in
        if numberInput {
            textField.keyboardType = .NumberPad
        }
    }

    let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
        let field = alert.textFields![0] as UITextField
        callback?(field.text!)
    }

    alert.addAction(OKAction)
    let CancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil)
    alert.addAction(CancelAction)
    view.presentViewController(alert,animated: true, completion: nil)
}

The error I get is in

callback?(field.text!)

The error is "Cannot convert value type of 'String' to expected argument type '()'. I know it's a matter of syntax - just don't know what it should be.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...