您的位置:首页 > 移动开发 > Swift

Swift 集合类型

2019-07-01 17:28 1376 查看

Swift 语言提供Arrays、Sets和Dictionaries三种基本的集合类型用来存储集合数据。数组(Arrays)是有序数据的集。集合(Sets)是无序无重复数据的集。字典(Dictionaries)是无序的键值对的集。

  • 集合的可变性
let 声明的不可变
var 声明的可变
  • 数组(Arrays)

1)创建一个空数组

var someInts = [Int]()

2)创建一个带有默认值的数组

var arr = Array(repeatElement(0.2, count: 3));

3)通过两个同类型数组相加创建一个新数组

var arr2 = Array(repeatElement(0.5, count: 3))
print(arr + arr2)

4)用数组字面量构造数组

var arr3 = ["apple", "orange", "pear"]

5)访问和修改数组
使用数组的只读属性count来获取数组中的数据项数量

print(" \(arr3.count)")

布尔属性isEmpty作为一个缩写形式去检查count属性是否为0

if arr3.isEmpty {
print("is empty.")
} else {
print("is not empty.")
}

使用append(_:)方法在数组后面添加新的数据项

arr3.append("333")

使用加法赋值运算符(+=)也可以直接在数组后面添加一个或多个拥有相同类型的数据项

arr3 += ["aaa","bbbb"]

根据索引访问

var firstItem = arr3[0]

根据索引修改

arr3[0] = "watermelon"

还可以利用下标来一次改变一系列数据值

arr3[0...2] = ["Bananas"]

调用数组的insert(_:at:)方法来在某个具体索引值之前添加数据项

arr3.insert("Maple Syrup", at: 0)

使用remove(at:)方法来移除数组中的某一项

let mapleSyrup = arr3.remove(at: 0)

最后一项移除

arr3.removeLast()

6)数组的遍历**

for item in arr3 {
print(item)
}
  • 集合(Sets)

集合(Set)用来存储相同类型并且没有确定顺序的值。当集合元素顺序不重要时或者希望确保每个元素只出现一次时可以使用集合而不是数组。

Hashable协议符合Equatable协议,所以遵循该协议的类型也必须提供一个"是否相等"运算符(==) 的实现。
这个Equatable协议要求任何符合 == 实现的实例间都是一种相等的关系。也就是说,对于a,b,c三个值来说,== 的实现必须满足下面三种情况:

a == a(自反性)
a == b意味着b == a(对称性)
a == b && b == c意味着a == c(传递性)
集合类型语法

Swift 中的Set类型被写为Set,这里的Element表示Set中允许存储的类型,和数组不同的是,集合没有等价的简化形式
1)创建和构造一个空的集合

var letters = Set<Character>()

2)用数组字面量创建集合

var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]

一个Set类型不能从数组字面量中被单独推断出来,因此Set类型必须显式声明
如果你想使用一个数组字面量构造一个Set并且该数组字面量中的所有元素类型相同,那么你无须写出Set的具体类型。

var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]

3)访问和修改一个集合
一个Set中元素的数量,可以使用其只读属性count:

print("\(favoriteGenres.count)")

使用布尔属性isEmpty作为一个缩写形式去检查count属性是否为0

if favoriteGenres.isEmpty {
print("As far as music goes, I'm not picky.")
} else {
print("I have particular music preferences.")
}

调用Set的insert(_:)方法来添加一个新元素:

favoriteGenres.insert("Jazz")

调用Set的remove(_:)方法去删除一个元素

if let removedGenre = favoriteGenres.remove("Rock") {
print("\(removedGenre)? I'm over it.")
} else {
print("I never much cared for that.")
}
// 打印 "Rock? I'm over it."

使用contains(_:)方法去检查Set中是否包含一个特定的值:

if favoriteGenres.contains("Funk") {
print("I get up on the good foot.")
} else {
print("It's too funky in here.")
}
// 打印 "It's too funky in here."

4)遍历一个集合
在一个for-in循环中遍历一个Set中的所有值。

for genre in favoriteGenres {
print("\(genre)")
}
// 打印 "It's too funky in here."

Set类型没有确定的顺序,为了按照特定顺序来遍历一个Set中的值可以使用sorted()方法,它将返回一个有序数组

for genre in favoriteGenres.sorted() {
print("\(genre)")
}
  • 集合操作

5)基本集合操作
集合(Set)用来存储相同类型并且没有确定顺序的值。当集合元素顺序不重要时或者希望确保每个元素只出现一次时可以使用集合而不是数组。

  • 使用intersection(_:)方法根据两个集合中都包含的值创建的一个新的集合。(交集)
  • 使用symmetricDifference(_:)方法根据在一个集合中但不在两个集合中的值创建一个新的集合。(1 - 交集)
  • 使用union(_:)方法根据两个集合的值创建一个新的集合。(相加 重复的去掉一个)
  • 使用subtracting(_:)方法根据不在该集合中的值创建一个新的集合。(第一集合去掉第二个集合存在的元素)
let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]

oddDigits.union(evenDigits).sorted()
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
oddDigits. intersection(evenDigits).sorted()
// []
oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
// [1, 9]
oddDigits. symmetricDifference(singleDigitPrimeNumbers).sorted()
// [1, 2, 9]

6)集合成员关系和相等
使用“是否相等”运算符(==)来判断两个集合是否包含全部相同的值。
使用isSubset(of:)方法来判断一个集合中的值是否也被包含在另外一个集合中。
使用isSuperset(of:)方法来判断一个集合中包含另一个集合中所有的值。
使用isStrictSubset(of:)或者isStrictSuperset(of:)方法来判断一个集合是否是另外一个集合的子集合或者父集合并且两个集合并不相等。
使用isDisjoint(with:)方法来判断两个集合是否不含有相同的值(是否没有交集)。

let houseAnimals: Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
let cityAnimals: Set = ["🐦", "🐭"]

houseAnimals.isSubset(of: farmAnimals)
// true
farmAnimals.isSuperset(of: houseAnimals)
// true
farmAnimals.isDisjoint(with: cityAnimals)
// true

  • 字典

1)字典类型简化语法
字典使用Dictionary<Key, Value>定义,其中Key是字典中键的数据类型,Value是字典中对应于这些键所存储值的数据类型。

注意:
一个字典的Key类型必须遵循Hashable协议,就像Set的值类型。

我们也可以用[Key: Value]这样简化的形式去创建一个字典类型。推荐后者。
2)创建一个空字典

var namesOfIntegers = [Int: String]()

3)用字典字面量创建字典

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

4)访问和修改字典
通过字典的只读属性count来获取某个字典的数据项数量:

print("\(airports.count)")

使用布尔属性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

updateValue(_:forKey:)这个方法返回更新值之前的原值

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.")
}
// 打印 "The name of the airport is Dublin Airport."
}

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

airports["APL"] = "Apple Internation"
// "Apple Internation" 不是真的 APL 机场, 删除它
airports["APL"] = nil
// APL 现在被移除了

removeValue(forKey:)方法也可以用来在字典中移除键值对,返回被移除的值或者在没有值的情况下返回nil:

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.")
}
// prints "The removed airport's name is Dublin Airport."

5)字典遍历
使用for-in循环来遍历某个字典中的键值对。每一个字典中的数据项都以(key, value)元组形式返回

for (airportCode, airportName) in airports {
print("\(airportCode): \(airportName)")
}
// YYZ: Toronto Pearson
// LHR: London Heathrow

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

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

使用某个字典的键集合或者值集合来作为某个接受Array实例的 API 的参数,可以直接使用keys或者values属性构造一个新数组:

let airportCodes = [String](airports.keys)
// airportCodes 是 ["YYZ", "LHR"]

let airportNames = [String](airports.values)
// airportNames 是 ["Toronto Pearson", "London Heathrow"]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: