集合(Sets):用来存储相同类型并且没有确定顺序的值。当集合元素顺序不重要时或者希望确保每个元素只出现一次时可以使用集合而不是数组。
创建和构造一个空的集合
var letters = Set<Character>()
print("letters is of type Set<Character> with \(letters.count) items.")
// 打印 "letters is of type Set<Character> with 0 items."
用数组字面量创建集合
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// favoriteGenres 被构造成含有三个初始值的集合
访问和修改一个集合
///获取Set中元素的数量
print("I have \(favoriteGenres.count) favorite music genres.")
///使用布尔属性isEmpty作为一个缩写形式去检查count属性是否为0
if favoriteGenres.isEmpty {
print("As far as music goes, I'm not picky.")
}
///添加一个新元素
favoriteGenres.insert("Jazz")
///删除一个元素
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."
///检查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."
遍历集合
///method1
for genre in favoriteGenres {
print("\(genre)")
}
///method2
//Swift 的Set类型没有确定的顺序,为了按照特定顺序来遍历一个Set中的值可以使用sorted()方法,它将返回一个有序数组,这个数组的元素排列顺序由操作符'<'对元素进行比较的结果来确定.
for genre in favoriteGenres.sorted() {
print("\(genre)")
}
// prints "Classical"
// prints "Hip hop"
// prints "Jazz
集合操作
- 使用
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]
集合成员关系和相等
- 使用“是否相等”运算符(
==
)来判断两个集合是否包含全部相同的值。 - 使用
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
转自:http://www.swift51.com/swift3.0.html