ios Swift 中的回调函数语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33290564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:04:25  来源:igfitidea点击:

Callback function syntax in Swift

iosswiftfunctioncallback

提问by Floyd Resler

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.

错误是“无法将 'String' 的值类型转换为预期的参数类型 '()'。我知道这是语法问题 - 只是不知道它应该是什么。

回答by Dan Beaulieu

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.

Rob 的回答是正确的,虽然我想分享一个简单的工作回调/完成处理程序的示例,但您可以下载下面的示例项目并尝试使用getBoolValue的输入。

download example project

下载示例项目

Swift 2:

斯威夫特 2:

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

getBoolValue(8) { (result) -> () in
    // do stuff with the result
    print(result)
}

Important to understand:

重要的是要理解:

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

回答by Anand Verma

try below code updated for Swift 3

尝试下面为 Swift 3 更新的代码

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

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

回答by álvaro Agüero

I use this way :

我用这种方式:

ViewController1

视图控制器1

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

ViewController2

视图控制器2

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

回答by rob mayoff

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

你已经声明callback不接受任何参数,然后你试图向它传递一个参数。

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

您指定了 type (()->(String))?,它是一个可选函数,不接受任何参数并返回一个String.

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

也许您的意思是指定((String)->())?,这是一个可选函数,它接受 aString并且不返回任何内容。

回答by stonesam92

In the parameters for showStandardPrompt, you declare callbackto have the type ()->(String), which is a function which takes no parameters and returns a String.

在 for 的参数中showStandardPrompt,您声明callback了 type ()->(String),它是一个不带参数并返回 a 的函数String

You then call it with field.text!as a parameter, which obviously conflicts with the previously given type.

然后将其field.text!作为参数调用,这显然与之前给定的类型冲突。

You need to correct the type given to callbackto take a Stringargument and return nothing:

您需要更正给定的类型callback以获取String参数并且不返回任何内容:

(String)->()