I read and tried the documentation, everything is clear, but not so in practice. Task: subtract another from one number using closures.

@IBAction func buttonLikePressed(sender: UIButton) { calculateLikes(50, newLikes: 1, operation:{$0 - $1}) } func calculateLikes(currentLikes:Int, newLikes: Int, operation: (Int, Int) -> Int) -> Int { return operation (currentLikes, newLikes) } 

I looked in the debugger, the line

 calculateLikes(50, newLikes: 1, operation:{$0 - $1}) 

It is called, but what it does is not clear. The result of the function = 50, not 49, as expected.

  • one
    can still without closures? return currentLikes-newLikes - Max Mikheyenko
  • and I have to use closures according to the condition - Anatoly

1 answer 1

caused, but what makes is not clear

To understand what is happening write the full form:

 @IBAction func buttonLikePressed(sender: UIButton) { print(calculateLikes(50, newLikes: 1, operation: operation)) } func calculateLikes(currentLikes:Int, newLikes: Int, operation: (Int, Int) -> Int) -> Int { return operation(currentLikes, newLikes) } func operation(currentLikes: Int, newLikes: Int) -> Int { return (currentLikes - newLikes) } 

You pass in calculateLikes 2 arguments and a function, get the result of the work of the passed function with the passed arguments and return it.

And according to your record - everything should work.