swift Dictionary

字典是一种存储多个相同类型的值的容器。每个值(value)都关联唯一的键(key),键作为字典中的这个值数据的标识符。字典中的数据项并没有具体顺序,我们在需要通过标识符(键)访问数据的时候使用字典。

创建一个空字典

var namesOfIntegers = [Int: String]()

// namesOfIntegers 是一个空的 [Int: String] 字典

访问和修改字典

和数组一样,我们可以通过字典的只读属性 来获取某个字典的数据项数量:

var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]

print("The dictionary of airports contains \(airports.count) items.")

// 打印 "The dictionary of airports contains 2 items."(这个字典有两个数据项)

使用布尔属性isEmpty来快捷地检查字典的count属性是否等于0:

if airports.isEmpty {

print("The airports dictionary is empty.")

} else {

print("The airports dictionary is not empty.")

}

// 打印 "The airports dictionary is not empty."

我们也可以在字典中使用下标语法来添加新的数据项

airports["LHR"] ="London"  // airports 字典现在有三个数据项

我们也可以使用下标语法来改变特定键对应的值:

airports["LHR"] = "London Heathrow"  // "LHR"对应的值 被改为 "London Heathrow

我们还可以使用下标语法来通过给某个键的对应值赋值为nil来从字典里移除一个键值对:

airports["LHR"] = nil  // LHR 现在被移除了

此外,removeValueForKey(_:)方法也可以用来在字典中移除键值对

字典遍历

我们可以使用for-in循环来遍历某个字典中的键值对。每一个字典中的数据项都以(key, value)元组形式返回,并且我们可以使用临时常量或者变量来分解这些元组:

for (airportCode, airportName) in airports {

print("\(airportCode): \(airportName)")

}

// YYZ: Toronto Pearson

// LHR: London Heathrow

通过访问 或者 属性,我们也可以遍历字典的键或者值:

for airportCode in airports.keys {

print("Airport code: \(airportCode)")

}

// Airport code: YYZ

// Airport code: LHR

for airportName in airports.values {

print("Airport name: \(airportName)")

}

// Airport name: Toronto Pearson

// Airport name: London Heathrow

如果我们只是需要使用某个字典的键集合或者值集合来作为某个接受 实例的 API 的参数,可以直接使用k或者 属性构造一个新数组:

let airportCodes = [String](airports.keys)

// airportCodes 是 ["YYZ", "LHR"]

let airportNames = [String](airports.values)

// airportNames 是 ["Toronto Pearson", "London Heathrow"]

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容