1

In Swift, the let keyword denotes immutability. What does it mean to the compiler why you combine let and NSMutable?

e.g.

let nsArray: NSMutableArray = ["a", "b"];
nsArray.addObject("c")  // Still works
Victor Sigler
  • 23,243
  • 14
  • 88
  • 105
Boon
  • 40,656
  • 60
  • 209
  • 315
  • 3
    Classes are *reference types*, thefore `nsArray.addObject("c")` does not change the value of `nsArray`. – Martin R Jun 01 '15 at 13:02

2 Answers2

3

NSMutableArray is a class so it's passed by reference, not by value: here what is constant is your nsArray object, not the mutable array it contains.

So you can do:

nsArray.addObject("c")

But you can't do:

nsArray = ["d", "e"]
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
2

Interesting question. This is because you're not assigning the array itself. If you instead did:

nsArray = ["a", "sb"]

Then you would get a compiler error. This is somewhat related to the discussion here: let Non-mutable array in swift

Community
  • 1
  • 1
Steffen D. Sommer
  • 2,896
  • 2
  • 24
  • 47