Swift - Modifying an Item in the Dictionary

Introduction

To replace the value of an item inside a dictionary, specify its key and assign a new value to it:

var myTable =  [
    "Apple": "iOS",
    "Google" : "Android",
    "Microsoft" : "Windows Phone"
]


myTable["Microsoft"] = "WinPhone"

If the specified key does not already exist in the dictionary, a new item is added.

If it already exists, its corresponding value is updated.

You can use the updateValue(forKey:) method and specify the new value for the item as well as its key:

myTable.updateValue("WinPhone", forKey: "Microsoft")

If a dictionary is created using the let keyword, you will not be able to modify the value of its members.

You can modify the values of a dictionary only if you declare it using the var keyword.

If the key specified does not exist in the dictionary, a new item will be added.

The updateValue(forKey:) method returns the old value for the specified item if that item already exists.

This enables you to check whether the item has been updated.

The updateValue(forKey:) method returns an optional value of the dictionary value type (String? in this example).

It will contain a string value if the item already exists and nil if the specified key is not found (meaning a new item is inserted).

You can use this to check whether the item has been updated or newly inserted:


if let oldValue = myTable.updateValue("WinPhone", forKey: "Microsoft")
{
    print("The old value for 'Microsoft' was \(oldValue).")
} else {
    print("New key inserted!")
}

var myTable =  [
    "Apple": "iOS",
    "Google" : "Android",
    "Microsoft" : "Windows Phone"
]

Related Topic