aldirc
aldirc

Reputation: 13

Swift Array var issue

    var dictionary = ["1": ["One","Two","Three"],
                      "2": ["A","B","C"]
                     ]

    var array = dictionary ["1"]
    array!.append("Four")

    print("array Count: \(array!.count) array In DictionaryCount: \(dictionary ["1"]!.count)")
    //array Count: 4 array In Dictionary Count: 3

var array has append "Four",but in dictionary it does't, how to append an element in dictionary?

Upvotes: 1

Views: 76

Answers (2)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52093

In Swift, arrays are implemented as structs and they are always copied when they are passed around in your code, and do not use reference counting. That being said, array becomes the copy of dictionary[1] in your example so updating the contents of that doesn't affect the original dictionary.

What you should do instead:

dictionary["1"]?.append("Four")

Upvotes: 2

alexburtnik
alexburtnik

Reputation: 7741

Unlike Objective-C, collections in Swift are not reference types. It means that arrays, dictionaries, strings and almost everything behave like primitives in C/Objective-C (except objects, which are instances of classes, not structures or enums)

You can find more details in this official Apple page: Value and Reference Types

Upvotes: 0

Related Questions