Callback function syntax in Swift

后端 未结 5 936
南旧
南旧 2020-12-08 10:12

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 showSt         


        
相关标签:
5条回答
  • 2020-12-08 10:31

    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
    
    0 讨论(0)
  • 2020-12-08 10:32

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

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

    You need to correct the type given to callback to take a String argument and return nothing:

    (String)->()
    
    0 讨论(0)
  • 2020-12-08 10:39

    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)
    })
    
    0 讨论(0)
  • 2020-12-08 10:42

    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.

    0 讨论(0)
  • 2020-12-08 10:51

    I use this way :

    ViewController1

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

    ViewController2

    var callback: ((_ id: Int) -> Void)?
    callback?(example_id)
    
    0 讨论(0)
提交回复
热议问题