Passing functions as parameters in Swift

前端 未结 4 1854
暖寄归人
暖寄归人 2021-02-05 00:17

I have the following function working as I expect, in iOS 8:

func showConfirmBox(msg:String, title:String,
    firstBtnStr:String,
    secondBtnStr:String,
    c         


        
4条回答
  •  梦如初夏
    2021-02-05 00:47

    Oneword answer for your question is Closures

    The Default Syntax for closures is () -> ()

    Instead of Selector you could directly mention the method definition

    func showConfirmBox(msg:String, title:String,
        firstBtnStr:String, firstSelector:(sampleParameter: String) -> returntype,
        secondBtnStr:String, secondSelector:() -> returntype,
        caller:UIViewController) {
        //Your Code
    }
    

    But using this will create readability problems so i suggest you to use typeAlias

    typealias MethodHandler1 = (sampleParameter : String)  -> Void
    typealias MethodHandler2 = ()  -> Void
    
    func showConfirmBox(msg:String, title:String,
                        firstBtnStr:String, firstSelector:MethodHandler1,
                        secondBtnStr:String, secondSelector:MethodHandler2) {
    
        // After any asynchronous call
        // Call any of your closures based on your logic like this
        firstSelector("FirstButtonString")
        secondSelector()
    }
    

    You can call your method like this

    func anyMethod() {
       //Some other logic 
    
       showConfirmBox(msg: "msg", title: "title", firstBtnStr: "btnString", 
             firstSelector: { (firstSelectorString) in
                  print(firstSelectorString) //this prints FirstButtonString
             }, 
             secondBtnStr: "btnstring") { 
               //Invocation comes here after secondSelector is called
    
             }
    }
    

提交回复
热议问题