Swift4.2_集合类型

官网链接

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"]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,496评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,407评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,632评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,180评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,198评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,165评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,052评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,910评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,324评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,542评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,711评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,424评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,017评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,668评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,823评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,722评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,611评论 2 353

推荐阅读更多精彩内容

  • 集合类型 Swift提供了三种主要的集合类型,称为数组,集合和字典,用于存储值的集合。数组是有序的值集合。集合是唯...
    Fuuqiu阅读 776评论 0 0
  • 1 .数组 Arrays 数组使用有序列表存储同一类型的多个值。相同的值可以多次出现在一个数组的不同位置中。这和O...
    iceMaple阅读 465评论 0 1
  • 这是16年5月份编辑的一份比较杂乱适合自己观看的学习记录文档,今天18年5月份再次想写文章,发现简书还为我保存起的...
    Jenaral阅读 2,752评论 2 9
  • 1.如何找到二叉树 两个叶子节点之间最长的距离http://blog.csdn.net/liuyi1207164...
    SpursGo阅读 297评论 0 0
  • 参考链接:https://www.cnblogs.com/zhun/p/5592205.html
    达_Ambition阅读 470评论 0 0