1
    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?

1
  • yes as said by @ozgur direct append will not work. you can do that or just reassign the array to dictionary["1"] = array Commented Oct 25, 2016 at 7:50

2 Answers 2

2

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")
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.