Swift Constants

Swift Constants

Use let to declare constants that don’t change.


Declare Constants

Use let to bind a value once so it cannot be reassigned later.

Example

let pi = 3.14159
let maxCount = 100
// pi = 4.0 // Error: cannot assign to value: 'pi' is a 'let' constant


Constants and Collections

If an array is bound with let, you can’t mutate (change) it.

Example

var nums = [1, 2]
nums.append(3)       // OK: nums is var
print(nums)

let fixed = [1, 2]
// fixed.append(3)  // Error if uncommented: cannot use mutating member on immutable value

Binding with let is immutable, so you can’t mutate it.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *