宣告字典
字典是鍵和值的無序集合。值與唯一鍵相關,並且必須屬於同一型別。
初始化 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"]