zs2020
zs2020

Reputation: 54543

Pass "function with parameter" as parameter

This doesn't compile

func showAlert(_ title: String, message: String, 
  onOk: (()->())? = nil,
  onAnotherAction:((anotherActionTitle : String)-> Void)? = nil) {
    let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)

    let ok = UIAlertAction(title: "OK", style: .default) { (action) in
        onOk?()
    }

    let anotherAction = UIAlertAction(title: anotherActionTitle, style: .default) { (action) in
        onAnotherAction?()
    }

    alertController.addAction(ok)
    alertController.addAction(anotherAction)

    ...
}

This compiles

func showAlert(_ title: String, message: String,
  onOk: (()->())? = nil,
  onAnotherAction:((String)-> Void)? = nil)

However, I have to declare another parameter for the title anotherActionTitle of onAnotherAction().

Is there a way make the first approach work? Thanks!

Upvotes: 0

Views: 72

Answers (2)

matt
matt

Reputation: 535989

However, I have to declare another parameter for the title anotherActionTitle of onAnotherAction()

No, you don't have to do that. Just make it a normal parameter of the function as a whole:

func showAlert(_ title: String, message: String,
               onOk: (()->())? = nil,
               anotherActionTitle: String? = nil,
               onAnotherAction: (()->())? = nil) {

The rest of your function will then compile and work correctly.

Upvotes: 1

Daniel Hall
Daniel Hall

Reputation: 13689

Since the implementation of SE-0111 as part of Swift 3, it is no longer possible to have named parameters for closure types.

There is a conceptual roadmap that the Swift core team has laid out for restoring named closure parameters at some point in the future, but no timeline for implementation that I am aware of:

https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160711/024331.html

Upvotes: 0

Related Questions