In Swift Language Tutorial for Beginner 7 - Dictionary, we understand the use of dictionary types in Swift, and now let’s take a look at collection types in Swift - Set.
Collections can be used to store unordered, non-duplicate data.
Declaration and initialization
1 | var set1:Set<Int> = [1,2,3,4] |
Note the differences with Array’s definition and initialization
Common operations
Determine the number of elements
Use the count property
1 | set1.count |
Determines whether the collection is empty
Use the isEmpty property
1 | if set1.isEmpty { |
Determines whether an element is included
1 | if set1.contains(1){ |
Add an element
1 | set1.insert(5) |
Delete the element
1 | set1.remove(1) |
Note: The 1 here is not the ordinal number (subscript), it is the 1 element
Delete all elements
1 | set1.removeAll() |
Collection operations
Suppose there are two sets
1 | var set3:Set<Int> = [1,2,3,4] |
Take the intersection
1 | var setInter = set3.intersection(set4) |
After the operation, setInter will contain {2, 1}
Take the union
1 | var setUni = set3.union(set4) |
After the operation, setUni will contain {4, 5, 6, 3, 1, 2}
Complement sets
1 | var setEx = set3.symmetricDifference(set4) |
After the operation, setEx will contain {4, 6, 3, 5}
Child collection judgment
Suppose there are several sets as follows:
1 | var set5:Set = [1,2] |
- Determining whether a subset of a set set5 is a subset of set7 returns ture
1 | set5.isSubset(of: set7) |
- The superset set7 that determines whether it is a set of sets is the superset of set5 returns the ture
1 | set7.isSuperset(of: set5) |
- Determines whether it is a true subset of a collection
set5 is a true subset of set7 returns to the form
1 | set5.isStrictSubset(of: set7) |
set7 is not a true superset of set8 returns false
1 | set7.isStrictSuperset(of: set8) |
Iterate over elements
You can use the for statement to traverse
1 | for item in set7 { |
You can also get the subscript of an element
1 | for index in set7.indices { |
You can also set the sort to traverse
1 | for item in set7.sorted(by: >){ |
Next
Next, we’ll take a brief look at Function in Swift.