Swift Object reference to array?

前端 未结 4 1187
面向向阳花
面向向阳花 2021-01-18 18:30

I probably missed an important information about swift. I have a map contains a key / swift array pair. I changed the array and the array inside the map was not changed. Cou

4条回答
  •  囚心锁ツ
    2021-01-18 18:40

    Array in Swift is defined as a struct, i.e. a value type. When you assign another variable to another variable of value type, it creates a copy of that second variable:

    map["list"] = list   // store a **copy** of list into map
    

    To see the difference between value and reference type, change your array to its ObjectiveC cousin, NSMutableArray, which is of reference type:

    var map = [String: NSMutableArray]()
    var list = NSMutableArray()
    map["list"] = list
    
    list.addObject("test")
    
    print(map)   // ["list": (test)]
    

提交回复
热议问题