0
let _ = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { (timer) in
    print("conunter \(counter += 1)")
}

Output:

conunter ()
conunter ()
conunter ()
.........

But if I do this

 let _ = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { (timer) in
    counter += 1
    print("conunter \(counter)")
}

It produces expected result. Why this is happening?

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
Muzahid
  • 5,072
  • 2
  • 24
  • 42
  • 2
    Somewhat related: [What was the reason for Swift assignment evaluation to void?](https://stackoverflow.com/questions/34173084/what-was-the-reason-for-swift-assignment-evaluation-to-void). – Martin R Jul 27 '17 at 07:11

2 Answers2

4

Because the particular function of the += operator has type inout Int and an Int, and returns (), a.k.a. Void

This is an intentional design decision implemented to discourage the use of mutating side-effects within other expressions. Your case is pretty much exactly what they hoped to prevent.

It may be annoying to have one extra line for this, but consider this: is it really the job of a print statement to increment a variable? That doesn't sound like "printing" to me.

Alexander
  • 59,041
  • 12
  • 98
  • 151
0

So basically += this is an operator overloading method just like c++ so it is a function that return type Void () mentioned by above answer, so it is print conunter ().

After performing the function statement it assigns the value of the counter so much easier to understand this, the second use of counter will have the value.

Salman Ghumsani
  • 3,647
  • 2
  • 21
  • 34