Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift dictionary nested array manipulation - cannot mutate nested array inside dictionary

var dict = ["alpha": ["a", "b", "c", "d"]]
// output : ["alpha": ["a", "b", "c", "d"]]

var alphaList = dict["alpha"]
// output : {["a", "b", "c", "d"]

alphaList?.removeAtIndex(1)
// output : {Some "b"}

alphaList
// output : {["a", "c", "d"]}

dict
// output : ["alpha": ["a", "b", "c", "d"]]

Why is 'dict' not altered? Is it because 'alphaList' is a copy of the array and not the actual array inside the dictionary? Can anyone point me where in Swift language documentation I can find this information?

What is the correct/functional way to manipulate values (of complex type) of a dictionary?

like image 369
mpprdev Avatar asked Feb 05 '26 01:02

mpprdev


2 Answers

Good question yes it creates the copy of the value in your case the value is Array

    var alphaList = dict["alpha"] 
/* which is the copy of original array 
changing it will change the local array alphaList as you can see by your output */
    output : {Some "b"}

In order to get the original array directly use

dict["alpha"]?.removeAtIndex(1)

Or update it using the key

alphaList?.removeAtIndex(1)
dict["alpha"] = alphaList 

Apple : Assignment and Copy Behavior for Strings, Arrays, and Dictionaries

Swift’s String, Array, and Dictionary types are implemented as structures. This means that strings, arrays, and dictionaries are copied when they are assigned to a new constant or variable, or when they are passed to a function or method.

This behavior is different from NSString, NSArray, and NSDictionary in Foundation, which are implemented as classes, not structures. NSString, NSArray, and NSDictionary instances are always assigned and passed around as a reference to an existing instance, rather than as a copy. "

like image 200
Rein rPavi Avatar answered Feb 07 '26 14:02

Rein rPavi


Swift arrays and dictionaries are value (struct) times. There are only one reference to such instance. While NSArray and NSDictonary are class type and there could be multiple references to such instances.

The statement var alphaList = dict["alpha"] makes copy for ["a", "b", "c", "d"], so you cannot change the original array.

If you want to mutate original "alpha" you have to use dict as root variable:

dict["alpha"]?.removeAtIndex(1)
like image 31
Kirsteins Avatar answered Feb 07 '26 14:02

Kirsteins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!