Swift

Swift教程之集合类型

2017-10-04  本文已影响2人  暗夜夜夜行路

集合类型

Swift有三种集合类型:数组、集合和字典。数组是有序集,集合是值唯一的无序集,字典是键值对的无序集。

`

let houseAnimals: Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
let cityAnimals: Set = ["🐦", "🐭"]
 
houseAnimals.isSubset(of: farmAnimals)
// true
farmAnimals.isSuperset(of: houseAnimals)
// true
farmAnimals.isDisjoint(with: cityAnimals)
// true

`

<br />

字典

字典存储相同类型的键和相同类型的值相关联的无序集。

注意

Swift的Dictionary类型与Foundation框架的NSDictionary类桥接。

字典类型简写语法

Dictionary类型写作Dictionary<Key, Value>,其中key为键类型,value为值类型。简写形式为[Key: Value],Swift官方建议优先使用简写形式。

注意

字典的键类型必须遵循Hashable协议。

创建空字典

使用初始化语法创建一个空字典:

var namesOfIntegers = [Int: String]()

若上下文已提供类型信息,可直接使用[:]语法给原字典重新设置为空:

namesOfIntegers[16] = "sixteen"
namesOfIntegers = [:]

使用字典字面量创建字典

通常通过字典字面量,即将一个或多个键值对写入字典来创建字典:

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

通过字典字面量可推断出字典中元素的键值类型,因此可忽略字典类型的声明:

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

获取和修改字典

通过其方法、属性或下标语法可获取和修改字典。

只读属性count获取字典的元素个数:

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

isEmpty属性判断字典元素个数是否为0:

if airports.isEmpty {
    print("The airports 字典为空.")
} else {
    print("The airports 字典不为空.")
}
// 打印 "The airports 字典不为空."

可直接通过下标语法为字典添加适当类型的新元素:

airports["LHR"] = "London"

下标语法用来修改字典中特定键的值:

airports["LHR"] = "London Heathrow"

updateValue(_:forKey:)方法用来更新或添加字典中特定键的值,若键存在,返回该值,若不存在,返回nil

if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
    print("The old value for DUB was \(oldValue).")
}

下标语法可以直接获取字典中特定键的值,返回值类型的可选值,值存在,返回该值,不存在,返回nil

if let airportName = airports["DUB"] {
    print("The name of the airport is \(airportName).")
} else {
    print("That airport is not in the airports dictionary.")
}

通过下标语法将特定键的值赋值为nil来删除字典中相应的键值对:

airports["APL"] = "Apple International"
airports["APL"] = nil

或者调用removeValue(forKey:)方法删除相应键值对,同样返回值的可选类型:

if let removedValue = airports.removeValue(forKey: "DUB") {
    print("The removed airport's name is \(removedValue).")
} else {
    print("The airports dictionary does not contain a value for DUB.")
}

字典遍历

使用for-in循环遍历字典元素,每次遍历以键值元组方式返回:

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

使用keysvalues属性将字典的所有键或值单独创建一个数组:

let airportCodes = [String](airports.keys)
// airportCodes is ["YYZ", "LHR"]
 
let airportNames = [String](airports.values)
// airportNames is ["Toronto Pearson", "London Heathrow"]

使用sorted()方法使字典按照从小到大顺序遍历。

上一篇下一篇

猜你喜欢

热点阅读