Declaring Dictionaries

suggest change

A dictionary is an unordered collection of keys and values. Each key is unique, and every value has the same type.

The full syntax for an empty dictionary is:

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

A shorter form:

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"]

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents