Swift Language Dictionaries Declaring Dictionaries

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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


Got any Swift Language Question?