Declaring Dictionaries

Download swift eBook


Dictionaries are an unordered collection of keys and values. Values relate to unique keys and must be of the same type.

When initializing a Dictionary the full syntax is as follows:

var books : Dictionary<Int, String> = Dictionary<Int, String>()

Although a more concise way of initializing:

var books = [Int: String]()
// or
var books: [Int: String] = [:]

Declare a dictionary with keys and values by specifying them in a comma separated list. The types can be inferred from the types of keys and values.

var books: [Int: String] = [1: "Book 1", 2: "Book 2"]
//books = [2: "Book 2", 1: "Book 1"] 
var otherBooks = [3: "Book 3", 4: "Book 4"]
//otherBooks = [3: "Book 3", 4: "Book 4"]


Contributors: 4
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial:

Download eBook