In the section Basic Operators, the Swift Programming Language guide states that ++ is a valid operator:
“More complex examples include the logical AND operator && (as in if enteredDoorCode && passedRetinaScan) and the increment operator ++i, which is a shortcut to increase the value of i by 1.”
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/gb/jEUH0.l
However, when attempting this in a playground;
import UIKit
let i = 0
i++
A build error shows:
swift Unary operator '++' cannot be applied to an operand of type 'Int'
Why?
Yeah, not the best-worded compiler error.
The problem is that you have declared i
using let
. Since integers are value types, this means i
is immutable – it cannot be changed once assigned a value.
If you declare i
as var i = 0
the code compiles.
You have defined i
as immutable with let
. Try var i = 0
instead.
Also, if you are changing the value of the variable of a value type (structures or enumerations) inside one of it's methods, you have to define that method as mutating:
mutating func modify() {
++i
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With