美文网首页
4、Swift 集合类型Collection Types

4、Swift 集合类型Collection Types

作者: Vergil_wj | 来源:发表于2017-08-22 18:59 被阅读28次

Swift提供三种主要集合类型:

  • Array:有序值数组
  • Set:无序唯一值集
  • Dictionary:无序键值对应关系字典
CollectionTypes_intro_2x.png

数组Arrays

1.创建数组
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"]
2.访问和修改数组
1.数组个数: count
print("The shopping list contains \(shoppingList.count) items.")
// Prints "The shopping list contains 2 items."

2.判断数组 count是否为0:
if shoppingList.isEmpty {
    print("The shopping list is empty.")
} else {
    print("The shopping list is not empty.")
}
// Prints "The shopping list is not empty."

3.通过 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

4.通过下标检索数组中的值
var firstItem = shoppingList[0]
// firstItem is equal to "Eggs"

通过下标修改数组中已经存在的值:
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

移除最后一个元素:
let apples = shoppingList.removeLast()
3.数组迭代
1.for-in 数组迭代:
for item in shoppingList {
    print(item)
}
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas

2.通过枚举 enumerated()方法获取索引和数值:
enumerated()方法返回的是一个元组(integer,item)

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

set:在集合中存储相同类型的,无序的值:
当元素的顺序不重要时,或你需要确定元素只出现一次时,可以使用 set 代替 array;

1.创建和初始化 Set
1.创建空 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>

2.通过字面数组创建 set
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// favoriteGenres has been initialized with three initial items

可以简化为:
var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]
2.访问和修改 set
1.set个数: count
print("I have \(favoriteGenres.count) favorite music genres.")
// Prints "I have 3 favorite music genres."

2.判断 set 是否为空:
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."

3.添加新元素: insert(_:)
favoriteGenres.insert("Jazz")
// favoriteGenres now contains 4 items

4.删除元素: 
remove(_:) :删除某个元素,只能通过元素来删除
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."
3.set的迭代
1.for-in: 打印出来是无序的
for genre in favoriteGenres {
    print("\(genre)")
}
// Jazz
// Hip hop
// Classical

2.set 没有默认排序,为了特殊排序的迭代,使用 sorted() 方法:相当于在数组排序中使用<操作
从小到大排序:
for genre in favoriteGenres.sorted() {
    print("\(genre)")
}
// Classical
// Hip hop
// Jazz
4.set运算演示
setVennDiagram_2x.png
基本集合运算:
intersection(_:) :  a和 b 公共部分;

symmetricDifference(_:) : a和 b 公共部分以外的部分;

union(_:) : a 和 b 之和;

subtracting(_:): 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]
集合成员关系
setEulerDiagram_2x.png

a是 b 的父集,b 是a 的子集, b 和 c 互斥

关系判断:
is equal: 判断两个集合是否相等;

isSubset(of:): 是否是其子集;

isSuperset(of:): 是否是其超集;

isStrictSubset(of:) or 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

dictionary: 一个键值关系的无序的集合;

1.创建字典
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"]
2.访问和修改字典
1.个数
print("The airports dictionary contains \(airports.count) items.")
// Prints "The airports dictionary contains 2 items."

2.判断是否为空
if airports.isEmpty {
    print("The airports dictionary is empty.")
} else {
    print("The airports dictionary is not empty.")
}
// Prints "The airports dictionary is not empty."

3.直接添加新成员
airports["LHR"] = "London"
// the airports dictionary now contains 3 items

4.修改成员
a.
airports["LHR"] = "London Heathrow"
// the value for "LHR" has been changed to "London Heathrow"

b.updateValue(_:forKey:)
通过 key 设置或更新值,执行这个方法后返回的是旧值.

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."

5.通过 key来访问成员
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."

6.删除成员
a.
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

b.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.")
}
// Prints "The removed airport's name is Dublin Airport."
3.字典迭代
键值对 key-value:
for (airportCode, airportName) in airports {
    print("\(airportCode): \(airportName)")
}
// YYZ: Toronto Pearson
// LHR: London Heathrow

键key:
for airportCode in airports.keys {
    print("Airport code: \(airportCode)")
}
// Airport code: YYZ
// Airport code: LHR

值 value:
for airportName in airports.values {
    print("Airport name: \(airportName)")
}
// Airport name: Toronto Pearson
// Airport name: London Heathrow

使用字典的键或值组成一个数组:
let airportCodes = [String](airports.keys)
// airportCodes is ["YYZ", "LHR"]
 
let airportNames = [String](airports.values)
// airportNames is ["Toronto Pearson", "London Heathrow"]

字典类型是无序的,想要排序使用 sorted()方法对键或值排序;

相关文章

网友评论

      本文标题:4、Swift 集合类型Collection Types

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