4

I need a closure method executed on demand.

In Swift 3 I used to do something like this:

// Declare closure
var checksPerformed: ((Void) -> Void)? // Declaration

// Call when needed
checksPerformed?() 

//Only executes when checksPerformed is called
checksPerformed = { _ in 
    // do stuff here
}

In Swift 4 this is no longer the case.

enter image description here

And after fixing this warning nothing works as before. What is the new way of doing this?

If I'm updating the declaration to: var checksPerformed: (() -> ())? I'm getting

enter image description here

kernelpanic
  • 2,876
  • 3
  • 34
  • 58

2 Answers2

6

Distinguish between single-tuple and multiple-argument function types

// Declare closure
var checksPerformed: (() -> ())? // Declaration

// Call when needed
checksPerformed?()

//Only executes when checksPerformed is called
checksPerformed = {
    // do stuff here
}
Nazmul Hasan
  • 10,130
  • 7
  • 50
  • 73
0

Use

var checksPerformed: (()->(Void))?

If you do that everything should work as expected.

Dont use the _ in when assigning the closure:

//Only executes when checksPerformed is called
checksPerformed = { 
    // do stuff here
}

//Call when needed
checksPerformed?() 
HixField
  • 3,538
  • 1
  • 28
  • 54
  • In the last paragraph I said I did. It didn't work. I'll update my original message to include the error. And I cannot do this: `` var checksPerformed: ()->(Void)?`` . The ``Class has no initializers`` is thrown – kernelpanic Jul 22 '17 at 11:00
  • You have to do (()->(Void))? this declares it as an optional closure; sorry in my org answer the ? Was part of the question sentence. – HixField Jul 22 '17 at 11:04
  • Updated the answer to made it more clear – HixField Jul 22 '17 at 11:07
  • Your answer is the same as in the comments below my questions. And it still doesn't work (see my updated answer with a screenshot) – kernelpanic Jul 22 '17 at 11:09
  • @kernelpanic Remove the `_ in`. There are no parameters. Do you know that `_` is a placeholder for a parameter? In your original code you actually had a closure with one parameter of type `Void`, not a closure without parameters. – Sulthan Jul 22 '17 at 11:09
  • I agree the _ should be removed in assigning the closure – HixField Jul 22 '17 at 11:12
  • Make sure you first assign the closure before calling it. In the code the order is wrong – HixField Jul 22 '17 at 11:14