Passing functions as parameters in Swift

前端 未结 4 694
广开言路
广开言路 2021-02-04 23:57

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:58

    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()
                                    }
    

提交回复
热议问题