How to set a function as function argument in Swift 3

前端 未结 3 365
轮回少年
轮回少年 2021-01-21 02:22

Q: Is it possible to pass a function as function argument in Swift 3?

To refactor my code, I want to have a global function. At the end of this function

相关标签:
3条回答
  • 2021-01-21 02:37

    Yes you can pass a function/closure as parameter of another function.

    This is the syntax

    func doSomething(closure: () -> ()) {
        closure()
    }
    

    here the function doSomething receives as parameter a closure with no params and no return type.

    You can call doSomething with this syntax

    doSomething(closure: { _ in print("Hello world") })
    

    Or using the trailing closure syntax

    doSomething { 
        print("Hello world")
    }
    
    0 讨论(0)
  • 2021-01-21 02:46

    Assuming

    typealias Func = () -> Void    
    

    You can do:

    func getButton(_ title: String, _ myFunc: Func) {
        let deleteButton = MIAlertController.Button(title: title, 
                                                    type: .cancel, 
                                                    config: getDestructiveButtonConfig(),
                                                    action: {
                                                        myFunc()
                                                    })
    }
    

    Or even:

    func getButton(_ title: String, _ myFunc: Func) {
        let deleteButton = MIAlertController.Button(title: title, 
                                                    type: .cancel, 
                                                    config: getDestructiveButtonConfig(),
                                                    action: myFunc
                                                    )
    }
    

    Also, if you haven't noticed, I moved closure to the end of parameter list. This way it will allow advanced magic like:

    getButton("X") { … }
    

    instead of

    getButton({ … }, "X")
    
    0 讨论(0)
  • 2021-01-21 03:02

    Functions are first class in swift so you can pass them like so:

    func getButton(_ myFunc: () -> Void, _ title: String) {
    

    You need to specify the signature of the function in the type, i.e. parameter types and return type

    0 讨论(0)
提交回复
热议问题