3

I upgraded to Swift 3.1, and I'm getting a few new errors that seem to be 3.1 syntax problems, as they weren't an issue before migration. Mostly they are related to closures, as in this example:

let alert = UIAlertController(title: "Success", message: "Thanks for participating in our raffle!", preferredStyle: UIAlertControllerStyle.alert)
                alert.addAction(UIAlertAction(title: "OK", style: .default, handler: {

                performSegue(withIdentifier: "to_root", sender: self)

            }))

Cannot convert value of type '() -> Void' to expected argument type '((UIAlertAction) -> Void)?'

Any ideas on how I could correct this to be able to compile my code at least in the short term?

Thanks.

Jacobo Koenig
  • 5,758
  • 5
  • 30
  • 54

2 Answers2

5

Input for your handler is of type (UIAlertAction) so just add following line to your code.

handler: {
                action in

Complete solution

let alertVC = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
        alertVC.addAction(UIAlertAction(title: "Ok", style: .default, handler: {
            action in
            self.performSegue(withIdentifier: "go", sender: self)
        }))
AkBombe
  • 598
  • 3
  • 10
  • 1
    Do you have any ideas why this is necessary in Swift 3.1, but wasn't in 3.0? – Jacobo Koenig Apr 24 '17 at 14:36
  • btw.. if you think the question might be relevant for other devs, I would appreciate an upvote. – Jacobo Koenig Apr 24 '17 at 14:36
  • you can check Api changes in Xcode. In Xcode 8.3 -> Help -> Api Changes – AkBombe Apr 24 '17 at 14:43
  • If two people have appreciated the answer then I think it is relevant. and its upto u whether u have to accept the answer or not. – AkBombe Apr 24 '17 at 14:46
  • 2
    Actually, SO protocol says that you should accept the first answer that fully answers your question, so the OP should definitely accept your answer. Up-voting is entirely optional(but strongly encouraged.) – Duncan C Apr 24 '17 at 16:09
  • You can also replace `action in` with `_ in` if you're not actually using the value. – John Montgomery Oct 22 '18 at 21:57
0

Post the entire block of code that is giving you an error. It sounds as though you are attempting to assign a closure to a variable rather than the result of that closure.

Try adding () at the end of your closure expression, which would cause the compiler to try to evaluate the closure and use it's return value rather than the closure itself:

TextRow(){ row in
                row.title = "First Name"
                row.placeholder = "John"
                row.add(rule: RuleRequired())
            }()
Duncan C
  • 115,063
  • 19
  • 151
  • 241
  • edited.. I found that its closures in general that are giving me trouble, so I added a more descriptive example. Your suggestion of adding () did not work. – Jacobo Koenig Apr 24 '17 at 13:32