Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of increment operator gives build error "swift Unary operator '++' cannot be applied to an operand of type 'Int'"

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?

like image 484
Max MacLeod Avatar asked Mar 26 '15 14:03

Max MacLeod


3 Answers

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.

like image 186
Airspeed Velocity Avatar answered Sep 20 '22 01:09

Airspeed Velocity


You have defined i as immutable with let. Try var i = 0 instead.

like image 22
GriffeyDog Avatar answered Sep 17 '22 01:09

GriffeyDog


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
}
like image 43
juanjo Avatar answered Sep 17 '22 01:09

juanjo