Set 集合
創(chuàng)建和初始化一個空集
var letters = Set<Character>()
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>
用數(shù)組字面值創(chuàng)建一個集合
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
訪問和修改一個集合
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."
將新項(xiàng)目添加到集合中
favoriteGenres.insert("Jazz")
從集合中移除一個項(xiàng)目,如果該項(xiàng)目是該集合的成員,則移除該項(xiàng)目,并返回移除的值,或者nil如果該集合不包含該項(xiàng)目,則返回該值。另外,一個集合中的所有項(xiàng)目都可以用它的removeAll()方法刪除。
if let removedGenre = favoriteGenres.remove("Rock") {
print("\(removedGenre)? I'm over it.")
} else {
print("I never much cared for that.")
}
集合是否包含特定的項(xiàng)目
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."
遍歷集合
for genre in favoriteGenres {
print("\(genre)")
}
Swift的Set類型沒有定義的順序。要按特定順序迭代集合的值,請使用sorted()方法
for genre in favoriteGenres.sorted() {
print("\(genre)")
}

setVennDiagram_2x.png
使用該intersection(:)方法創(chuàng)建一個只有兩個集合通用的值的新集合。
使用該symmetricDifference(:)方法創(chuàng)建一個新的集合中的值,而不是兩個。(a,b集合去掉共同部分)
使用該union(:)方法創(chuàng)建一個包含兩個集合中所有值的新集合。
使用該subtracting(:)方法創(chuàng)建一個新的集合,其值不在指定的集合中。(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]
集合關(guān)系
使用“is equal”運(yùn)算符(==)來確定兩個集合是否包含所有相同的值。
使用該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