Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can NSMutableArray add object using let in swift

I created a NSMutableArray in swift using let and when I add addObject in the mutableArray then it will add it even though I used the let to assign a constant. Can anyone explain how let works in swift? If it doesn't allow you to add value in later then how is the following code working?

let arr : NSMutableArray = [1,2,3,4,5]
arr.addObject(6)
println(arr)
like image 327
abhiDagwar Avatar asked Jul 24 '15 08:07

abhiDagwar


2 Answers

Classes are reference types, and NSMutableArray is a class.

Foundation's NSMutableArray is different from Swift's Array: the latter is a value type.

If you create a constant NSMutableArray:

let ns: NSMutableArray = ["a", "b"]

then this works:

ns.addObject("c")

but this doesn't:

ns = ["d", "e"]   // nope!

because you can change the content of the reference but you can't change what is assigned to the constant.

On the other hand, with Swift's Array:

let sw: [String] = ["a", "b"]

the constant can't be changed because it's a value, not a reference.

sw.append("c")   // nope!

Doc: Structures and Enumerations Are Value Types and Classes Are Reference Types

like image 81
Eric Aya Avatar answered Oct 23 '22 09:10

Eric Aya


disclaimer: this answer only applies to NS type data structures, please see @Eric D's answer for the full picture

let when used with a class just means the variable cant be changed, eg, to another array. If you dont want the array to be editable, use a normal NSArray and not a mutable one

let arr : NSMutableArray = [1,2,3,4,5]
arr = [1,2,3,4,5] //error trying to assign to a let variable that has already been assigned

arr.addObject(6) //fine because we are not changing what is assigned to arr, but we are allowed to change the object that is assigned to arr itself

I think your understanding of what a constant variable is, is a bit too strict.

like image 44
Fonix Avatar answered Oct 23 '22 08:10

Fonix