Passing functions as parameters in Swift

前端 未结 4 1852
暖寄归人
暖寄归人 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

    Just in case anyone else stumbles upon this. I worked out an updated simple solution for Swift 5.1 while I was working through this for while building a global alert utility for a project.

    Swift 5.1

    Function with Closure:

    func showSheetAlertWithOneAction(messageText: String, dismissButtonText: String, actionButtonText : String, presentingView : NSWindow, actionButtonClosure: @escaping () -> Void) {
            let alert = NSAlert()
            alert.messageText = messageText
            alert.addButton(withTitle: actionButtonText)
            alert.addButton(withTitle: dismissButtonText)
            alert.beginSheetModal(for: presentingView) { (response) in
                if response == .alertFirstButtonReturn {
                    actionButtonClosure()
                }
            }
        }
    

    Function Called:

    showSheetAlertWithOneAction(messageText: "Here's a message", dismissButtonText: "Nope", actionButtonText: "Okay", presentingView: self.view.window!) {
                                                someFunction()
                                    }
    

提交回复
热议问题