2

Can we change any pair value in let type Dictionary in Swift Langauage.

like :

let arr2 : AnyObject[] = [1, "23", "hello"]
arr2[1] = 23  
arr2 // output: [1,23,"hello"]


let arr1 :Dictionary<Int,AnyObject> = [1: "One" , 2 : 2]
arr1[2] = 4 // not posible error
arr1

In Case of Immutable Array we can change its value like above but not in case of Immutable Dictionary. Why?

Mohit Jethwa
  • 613
  • 2
  • 6
  • 14
  • http://stackoverflow.com/questions/24096096/immutable-mutable-collections-in-swift/24096192#24096192. It is not a dupe, simply it has some useful info. – nicael Jun 26 '14 at 11:35
  • 1
    The bottom line answer is that Apple has chosen a very bad and inconsistent definition of "immutable" when it comes to Array, and that inconsistent definition is, for better or worse, not carried over to Dictionary. – David Berry Jun 26 '14 at 18:49

3 Answers3

4

This is taken from The Swift Programming Language book:

For dictionaries, immutability also means that you cannot replace the value for an existing key in the dictionary. An immutable dictionary’s contents cannot be changed once they are set.

Immutability has a slightly different meaning for arrays, however. You are still not allowed to perform any action that has the potential to change the size of an immutable array, but you are allowed to set a new value for an existing index in the array.

Greg
  • 25,317
  • 6
  • 53
  • 62
2

Array declared with let has only immutable length. Contents can still be changed.
Dictionary declared with let is completely immutable, you can't change contents of it. If you want, you must use var instead of let.

nicael
  • 18,550
  • 13
  • 57
  • 90
1

Swift has changed a lot since then.

Array and Dictionary are value types. When declared with let, they cannot change any more. Especially, one cannot re-assign them, or the elements in them.

But if the type of the elements is reference type, you can change the properties of the elements in Array or Dictionary.

Here is a sample.(run in Xcode6 beta-6)

class Point {
    var x = 0
    var y = 0
}

let valueArr: [Int] = [1, 2, 3, 4]
let refArr: [Point] = [Point(), Point()]

valueArr[0] = -1 // error
refArr[0] = Point() // error
refArr[0].x = 1

let valueDict: [Int : Int] = [1: 1, 2: 2]
let refDict: [Int: Point] = [1: Point(), 2: Point()]
valueDict[1] = -1 //error
refDict[1] = Point() //error
refDict[1]!.x = -1
Windor C
  • 1,120
  • 8
  • 17