Swift Language Tutorial for Beginner 8 - Set

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

1
set1.count

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

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
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]
  1. Determining whether a subset of a set set5 is a subset of set7 returns ture
1
set5.isSubset(of: set7)
  1. 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)
  1. 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.

本文标题:Swift Language Tutorial for Beginner 8 - Set

文章作者:Morning Star

发布时间:2022年01月17日 - 07:01

最后更新:2022年01月17日 - 08:01

原始链接:https://www.mls-tech.info/app/swift/swift-tutorial-8-set-en/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。