Swift-集合类型
Swift提供了三种主要的集合类型,称为数组,集合和字典,用于存储值的集合。数组是值的有序集合。集是唯一值的无序集合。字典是键-值关联的无序集合
image.pngSwift中的数组,集合和字典始终清楚它们可以存储的值和键的类型。这意味着您不能将错误类型的值错误地插入到集合中。这也意味着您可以确定将从集合中检索的值的类型。
集合的可变性
如果创建数组,集合或字典,并将其分配给变量,则创建的集合将是mutable。这意味着您可以在创建集合后通过添加,删除或更改集合中的项目来更改(或变异)集合。如果将数组,集合或字典分配给常量,则该集合是不可变的,并且其大小和内容无法更改
数组
创建一个空数组
var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) items.")
// Prints "someInts is of type [Int] with 0 items."
创建具有默认值的数组
Swift的Array类型还提供了一个初始化程序,用于创建一个特定大小的数组,并将其所有值设置为相同的默认值。您向初始化程序传递了适当类型的默认值(称为repeating):以及该值在新数组中重复的次数(称为count)
var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]
您可以使用加法运算符(+)将两个具有兼容类型的现有数组加在一起,从而创建一个新数组。从添加到一起的两个数组的类型推断出新数组的类型:
var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]
print(threeDoubles)
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]
print(sixDoubles)
您可以通过调用数组的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
image.png
image.png
如上图 推断是是字符呢串 ,所以不能插入00
插入第一个元素
shoppingList.insert("00", at: 0)
print(shoppingList)
删除第一个元素
shoppingList.remove(at: 0)
遍历数组
for item in shoppingList {
print(item)
}
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas
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
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")
print(letters)
//删除一个值
letters.remove("a")
print(letters)
执行集合操作
image.png
使用该intersection(:)方法创建仅具有两个集合共有的值的新集合。
使用该symmetricDifference(:)方法创建一个新集合,其中两个集合中都有一个值,但不能同时包含两个集合中的值。
使用该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]
设定会员资格和平等
image.png
使用“等于”运算符(==)确定两组是否包含所有相同的值。
使用该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
Dictionary
创建一个空字典
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]
用字典文字创建字典
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
访问和修改字典
airports["LHR"] = "London"
// the airports dictionary now contains 3 items
airports["LHR"] = "London Heathrow"
// the value for "LHR" has been changed to "London Heathrow"
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."
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."
遍历字典
for (airportCode, airportName) in airports {
print("\(airportCode): \(airportName)")
}
// LHR: London Heathrow
// YYZ: Toronto Pearson
for airportCode in airports.keys {
print("Airport code: \(airportCode)")
}
// Airport code: LHR
// Airport code: YYZ
for airportName in airports.values {
print("Airport name: \(airportName)")
}
// Airport name: London Heathrow
// Airport name: Toronto Pearson
let airportCodes = [String](airports.keys)
// airportCodes is ["LHR", "YYZ"]
let airportNames = [String](airports.values)
// airportNames is ["London Heathrow", "Toronto Pearson"]
OK Swift-集合类型 分享到此 。