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.