Swift learning: Swift programming tour-Sets of Collection types (7) and swiftsets
Sets are unordered values of the same type. You can use Sets to replace arrays when order is not important, or if you need to appear the same value only once in the set.
I. Sets type syntax
WritingSet <Element>,ElementIs the type of sets that can be stored
Create and initialize an empty 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.
If you can infer the type of its elements, you can also write
letters = []
Use the array literal to create a set
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]// favoriteGenres has been initialized with three initial items
Or (because it can be inferred as set <String>)
var favoriteGenres:Set = ["Rock", "Classical", "Hip hop"]// favoriteGenres has been initialized with three initial items
Access and modify
The count method returns the number of set data items.
print("I have \(favoriteGenres.count) favorite music genres.")// Prints "I have 3 favorite music genres.
IsEmpty checks whether set is empty
Contains (_ :) check whether the set object contains specific data.
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.
Add new data item
Insert (_ :) Add new data to an existing set object
favoriteGenres.insert("Jazz")// favoriteGenres now contains 4 items
Delete existing data items
Remove (_ :) delete existing data from an existing set object
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.
Traverse set
Use the forin statement to traverse the set
for genre in favoriteGenres { print("\(genre)")}// Classical// Jazz// Hip hop
Set unordered data storage. You can use sort () to sort data in ascending order.
Intersect (_ :) creates a new set object that contains data shared by two Set objects.
ExclusiveOr (_ :) is a new set object that does not contain data shared by two Set objects.
Union (_ :) creates a new set object that contains all the data of two Set objects.
Subtract (_ :) creates a new set object that only contains one of the existing Set data.
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).sort()// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]oddDigits.intersect(evenDigits).sort()// []oddDigits.subtract(singleDigitPrimeNumbers).sort()// [1, 9]oddDigits.exclusiveOr(singleDigitPrimeNumbers).sort()// [1, 2, 9]
= The operator compares whether the values of the two sets are all the same
let houseAnimals: Set = ["