美文网首页iOS劝退指南
Swift4.2_集合类型

Swift4.2_集合类型

作者: 鼬殿 | 来源:发表于2018-11-23 18:07 被阅读14次

官网链接

image.png
  • 数组 (Arrays)

1.创建一个空的数组

var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) items.")
// Prints "someInts is of type [Int] with 0 items."

someInts.append(3)
// someInts now contains 1 value of type Int
someInts = []
// someInts is now an empty array, but is still of type [Int]

2.创建具有默认值的数组

var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]

3.将两个数组加起来,创建一个新的数组

您可以通过使用加法运算符(+)将两个具有兼容类型的现有数组相加来创建新数组。 新数组的类型是从您添加的两个数组的类型推断出来的:

var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
// anotherThreeDoubles is of type [Double], and equals [2.5, 2.5, 2.5]

var sixDoubles = threeDoubles + anotherThreeDoubles
// sixDoubles is inferred as [Double], and equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]

4.创建具有数组类型的数组

var shoppingList: [String] = ["Eggs", "Milk"]
// shoppingList has been initialized with two initial items
var shoppingList = ["Eggs", "Milk"]

5.访问和修改数组

print("The shopping list contains \(shoppingList.count) items.")
// Prints "The shopping list contains 2 items."

if shoppingList.isEmpty {
    print("The shopping list is empty.")
} else {
    print("The shopping list is not empty.")
}
// Prints "The shopping list is not empty."

您可以通过调用数组的append(_ :)方法将新项添加到数组的末尾:

shoppingList.append("Flour")
// shoppingList now contains 3 items, and someone is making pancakes

或者,使用加法赋值运算符(+ =)追加一个或多个兼容项的数组:

shoppingList += ["Baking Powder"]
// shoppingList now contains 4 items
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
// shoppingList now contains 7 items

使用下标语法从数组中检索值,在数组名称后面的方括号内传递要检索的值的索引:

var firstItem = shoppingList[0]
// firstItem is equal to "Eggs"

Note
数组中的第一项索引为0,而不是1. Swift中的数组始终为零索引。

您可以使用下标语法来更改给定索引处的现有值:

shoppingList[0] = "Six eggs"
// the first item in the list is now equal to "Six eggs" rather than "Eggs"

您还可以使用下标语法一次更改值范围,即使替换值集的长度与要替换的范围不同。 以下示例将“Chocolate Spread”,“Cheese”和“Butter”替换为“Bananas”和“Apples”:

shoppingList[4...6] = ["Bananas", "Apples"]
// shoppingList now contains 6 items

要在指定索引处将项插入数组,请调用数组的insert(_:at :)方法:

shoppingList.insert("Maple Syrup", at: 0)
// shoppingList now contains 7 items
// "Maple Syrup" is now the first item in the list

同样,您使用remove(at :)方法从数组中删除项

let mapleSyrup = shoppingList.remove(at: 0)
// the item that was at index 0 has just been removed
// shoppingList now contains 6 items, and no Maple Syrup
// the mapleSyrup constant is now equal to the removed "Maple Syrup" string

Note
如果尝试访问或修改数组现有边界之外的索引的值,则会触发运行时错误。 通过将索引与数组的count属性进行比较,可以在使用索引之前检查索引是否有效。 数组中最大的有效索引是count-1,因为数组是从零开始索引的 , 但是,当count0(意味着数组为空)时,没有有效的索引。

如果要从数组中删除最终项,请使用removeLast()方法而不是remove(at :)方法,以避免需要查询数组的count属性。 与remove(at :)方法一样,removeLast()返回已删除的项:

let apples = shoppingList.removeLast()
// the last item in the array has just been removed
// shoppingList now contains 5 items, and no apples
// the apples constant is now equal to the removed "Apples" string

6.数组的遍历

for item in shoppingList {
    print(item)
}
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas

数组的索引和value
for (index, value) in shoppingList.enumerated() {
    print("Item \(index + 1): \(value)")
}
// Item 1: Six eggs
// Item 2: Milk
// Item 3: Flour
// Item 4: Baking Powder
// Item 5: Bananas
  • 集合(Sets)

Sets在没有定义顺序的集合中存储相同类型的不同值

NOTE
Swift的Set类型被桥接到Foundation的NSSet类。

1.集合类型的哈希值
类型必须是可散列的才能存储在集合中 - 即,类型必须提供计算自身散列值的方法。 哈希值是一个Int值,对于所有同等比较的对象都是相同的,这样如果a == b,则遵循a.hashValue == b.hashValue。

默认情况下,Swift的所有基本类型(如String,Int,Double和Bool)都是可清除的,并且可以用作设置值类型或字典键类型。 默认情况下,没有关联值的枚举大小写值(如枚举中所述)也是可以清除的。

2.设置类型语法
Swift集的类型写为Set <Element>,其中Element是允许该集存储的类型。 与数组不同,集合没有等效的简写形式。

3.初始化创建空的set
您可以使用初始化语法创建某个类型的空集:

var letters = Set<Character>()
print("letters is of type Set<Character> with \(letters.count) items.")
// Prints "letters is of type Set<Character> with 0 items."

或者,如果上下文已经提供了类型信息,例如函数参数或已经键入的变量或常量,则可以使用空数组文字创建一个空集:

letters.insert("a")
// letters now contains 1 value of type Character
letters = []
// letters is now an empty set, but is still of type Set<Character>

4.创建一个数组类型的集合

var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// favoriteGenres has been initialized with three initial items

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

5.访问和修改集Set

您可以通过其方法和属性访问和修改集。
要查找集合中的项目数,请检查其只读计数属性:

print("I have \(favoriteGenres.count) favorite music genres.")
// Prints "I have 3 favorite music genres."

使用Boolean isEmpty属性作为检查count属性是否等于0的快捷方式:

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

您可以通过调用setinsert(_ :)方法将新项添加到集合中:

favoriteGenres.insert("Jazz")
// favoriteGenres now contains 4 items

您可以通过调用setremove(_ :)方法从集合中删除项目,如果该项目是该集合的成员,则删除该项目,并返回已删除的值,如果该集合不包含该项目,则返回nil。 或者,可以使用removeAll()方法删除集合中的所有项目。

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

要检查集合是否包含特定项目,请使用contains(_ :)方法。

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

6.集合的遍历

for genre in favoriteGenres {
    print("\(genre)")
}
// Classical
// Jazz
// Hip hop

SwiftSet类型没有定义的顺序。 要以特定顺序迭代集合的值,请使用sorted()方法,该方法将集合的元素作为使用<运算符排序的数组返回。

for genre in favoriteGenres.sorted() {
    print("\(genre)")
}
// Classical
// Hip hop
// Jazz

7.集合的基本操作
下图描述了两个集合ab,阴影区域表示了各种集合操作的结果。

image.png

使用交集intersection(:) A和B的交集,写作A∩B,是既属于A的、又属于B的所有元素组成的集合。
使用对称差集symmetricDifference(
:) A△B = (A-B)∪(B-A)。
使用并集union(:) A和B的并集是将A和B的元素放到一起构成的新集合。
使用差级subtracting(
:) A - B称为B对于A的差集,是属于A的、但不属于B的所有元素组成的集合。
特意补了一下集合的知识点,不容易啊😊

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]

8.集合成员与等式
下图描述了三个集合(abc),它们的重叠区域表示集合之间共享的元素。 set aset b的超集,因为set a包含set b中的所有元素。 相反,set bset a的子集,因为b中的所有元素也包含在a中。 集合b和集合c彼此不相交,因为它们没有共同的元素。

image.png
使用“is equal”运算符(==)确定两个集合是否包含所有相同的值。
使用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
  • 字典(Dictionaries)

1.创建一个空的字典
与数组一样,您可以使用初始化语法创建特定类型的空字典:

var namesOfIntegers = [Int: String]()
// namesOfIntegers is an empty [Int: String] dictionary

namesOfIntegers[16] = "sixteen"
// namesOfIntegers now contains 1 key-value pair
namesOfIntegers = [:]
// namesOfIntegers is once again an empty dictionary of type [Int: String]

2.创建字典类型的字典

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

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

3.访问和修改字典
您可以通过其方法和属性或使用下标语法来访问和修改字典。
与数组一样,您可以通过检查其只读计数属性来查找字典中的项目数:

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

使用Boolean isEmpty属性作为检查count属性是否等于0的快捷方式:

if airports.isEmpty {
    print("The airports dictionary is empty.")
} else {
    print("The airports dictionary is not empty.")
}
// Prints "The airports dictionary is not empty."

您可以使用下标语法将新项添加到字典中。 使用适当类型的新键作为下标索引,并指定适当类型的新值:

airports["LHR"] = "London"
// the airports dictionary now contains 3 items

您还可以使用下标语法来更改与特定键关联的值:

airports["LHR"] = "London Heathrow"
// the value for "LHR" has been changed to "London Heathrow"

作为下标的替代方法,使用字典的updateValue(_:forKey :)方法来设置或更新特定键的值。 与上面的下标示例一样,updateValue(_:forKey :)方法设置键的值(如果不存在),或者如果该键已存在则更新该值。 但是,与下标不同,updateValue(_:forKey :)方法在执行更新后返回旧值。 这使您可以检查是否发生了更新。
updateValue(_:forKey :)方法返回字典值类型的可选值。 例如,对于存储String值的字典,该方法返回String?“optional String”类型的值。 如果在更新之前存在该键,则此可选值包含该键的旧值;如果不存在任何值,则该值包含nil

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

您还可以使用下标语法从字典中检索特定键的值。 因为可以请求不存在值的键,所以字典的下标返回字典值类型的可选值。 如果字典包含所请求键的值,则下标返回包含该键的现有值的可选值。 否则,下标返回nil

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

您可以使用下标语法通过为该键指定值nil来从字典中删除键值对:

airports["APL"] = "Apple International"
// "Apple International" is not the real airport for APL, so delete it
airports["APL"] = nil
// APL has now been removed from the dictionary

或者,使用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."

4.字典的遍历
您可以使用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

如果您需要使用带有Array实例的API的字典键或值,请使用keysvalues属性初始化新数组:

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

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

相关文章

  • Swift4.2_集合类型

    官网链接 数组 (Arrays) 1.创建一个空的数组 2.创建具有默认值的数组 3.将两个数组加起来,创建一个新...

  • iOS 深拷贝浅拷贝

    一,集合类型(NSArray、NSDictionary、NSSet等类型)与非集合类型(NSString等类型) ...

  • #python基础入门#04

    <组合数据类型> 集合类型序列类型(字符串,元组,列表)字典类型 集合类型:集合是多个元素的无序组合 特点:无序,...

  • redis 基本使用

    什么是redis 键值类型 String字符类型 map散列类型 list列表类型 set 集合类型 有序集合类型...

  • hive集合类型

    hive集合类型集合类型主要包括:array,map,struct等,hive的特性支持集合类型,这特性是关系型数...

  • 集合类型

    Collection 类型 Collection Type 数组(Array),字典(Dictionary),集合...

  • 集合类型

    上一篇:控制流当前篇:集合类型下一篇:基础大杂烩 这一课我们将学习更加抽象的数据类型:集合类型 ,集合类型是用来存...

  • 集合类型

    集合类型 Swift提供了三种主要的集合类型,称为数组,集合和字典,用于存储值的集合。数组是有序的值集合。集合是唯...

  • 集合类型

    Swift提供了三种基本的几个类型,也就是我们熟知的数组Array,集合Set,字典dictionary,用来...

  • 集合类型

    1有序可重复 1.1Array数组 一旦定义,数组的大小不可变,其中的元素类型不可变 1.2 MutableLis...

网友评论

    本文标题:Swift4.2_集合类型

    本文链接:https://www.haomeiwen.com/subject/igbjqqtx.html