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 2
| var set1:Set<Int> = [1,2,3,4] var set2 = Set(arrayLiteral: 1,2,3,4)
|
Note the differences with Array’s definition and initialization
Common operations
Determine the number of elements
Use the count property
Determines whether the collection is empty
Use the isEmpty property
1 2 3
| if set1.isEmpty { print("集合为空") }
|
Determines whether an element is included
1 2 3
| if set1.contains(1){ print("集合包含") }
|
Add an element
Delete the element
Note: The 1 here is not the ordinal number (subscript), it is the 1 element
Delete all elements
Collection operations
Suppose there are two sets
1 2
| var set3:Set<Int> = [1,2,3,4] var set4:Set<Int> = [1,2,5,6]
|
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 2 3 4
| var set5:Set = [1,2] var set6:Set = [2,3] var set7:Set = [1,2,3] var set8:Set = [1,2,3]
|
- Determining whether a subset of a set set5 is a subset of set7 returns ture
- 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 2 3
| for item in set7 { print(item) }
|
You can also get the subscript of an element
1 2 3
| for index in set7.indices { print(set7[index]) }
|
You can also set the sort to traverse
1 2 3
| for item in set7.sorted(by: >){ print(item) }
|
Next
Next, we’ll take a brief look at Function in Swift.