Sunday, September 13, 2015

Arrays & Dictionaries

Unlike their ObjC counterparts, Arrays and Dictionaries in SWIFT are value types. As long as keys and values are not reference types, both arrays and dictionaries will stay on as value types

var itemsToBuy = ["Coffee":"200 gm", "Tea": "100 gm", "Hot Chocolate": "500 gm"]

for (index, value) in itemsToBuy.enumerate() {
    print("Item: \(index) + quantity: \(value)")
}

var copiedItemsToBuy = itemsToBuy
copiedItemsToBuy["Coffee"] = "100 gm"

With this change, its only copiedItemsToBuy has changed, items ToBuy, remains as it is, which is what copy by value means

Behavior of Arrays are slightly different
var items = ["books", "pens", "notebook"]

func printArray(items:[AnyObject]) {
    for (index, item) in items.enumerate() {
        print("Index: \(index), Value:\(item)")
    }
}

var copiedItems = items

Any changes done to copiedItems is reflected in "items", unless there is an addition or deletion of items. In short, unless there is change to the overall count of items contents are shared.

There were a few methods in the past that would work, but are no longer working
1. unshare
2. copy
3. compare and contrast addresses === & !==

May be those will get back to work sooner.

No comments: