Swift - Mutability of Dictionaries

Introduction

When creating a dictionary, its mutability depends on whether you use either the let or the var keyword.

If you use the let keyword, the dictionary is immutable: its size cannot be changed after it has been created, as you are creating a constant.

If you use the var keyword, the dictionary is mutable: its size can be changed after its creation, as you are creating a variable.

Demo

var products = [
     "Apple" : ["iPhone", "iPad", "iPod touch"],
     "Google" :  ["Nexus S", "Nexus 4", "Nexus 5"],
     "Microsoft" : ["Lumia 920", "Lumia 1320","Lumia 1520"]
]

products["Apple"] = ["A", "B", "C"]

var models = products["Apple"]
if models != nil {
    print(models![0])   //iPhone
}

Result

Related Topic