声明字典

字典是键和值的无序集合。值与唯一键相关,并且必须属于同一类型。

初始化 Dictionary 时,完整语法如下:

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

虽然更简洁的初始化方式:

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

通过在逗号分隔列表中指定密钥和值来声明字典。可以从键和值的类型推断出类型。

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