Author: Thomas Hanning, original link, original date: 2018-09-06

Translator: rsenjoyer; Proofreading: NUMbbbbb, PMST; Finalized: Forelax

A Set is one of the Swift collection types used to store values of the same type that are unique in no definite order. You can think of a set as a box of billiard balls: they are unique in color and number, but are unordered within the box.

Tip: This article uses Swift 4 and Xcode 10

Create a collection

Creating a collection is very simple:

let setA: Set<String> = ["a"."b"."c"]
Copy the code

In this example, create a collection of type String and name it setA. It stores a, B, and C. In contrast to arrays, the elements of a collection are unordered. Using the compiler’s type derivation, you can also create collections as follows:

let setB: Set = ["a"."b"."c"]
Copy the code

We can also use the collection constructor:

let setC = Set(["a"."b"."c"])
Copy the code

Like arrays, if you define a collection using lets, it is immutable. What you define with var is a mutable collection.

var setD = Set(["a"."b"])
Copy the code

We’ll learn more about mutable collections later.

Access elements in the collection

You can use loops to access elements in a collection:

for value in setA {
     print(value)
}
Copy the code

Note: The order of values in the loop may be different each time the code is run. On the surface, they look like random returns.

Collection analysis

First, you can check if the collection is empty:

print(setA.isEmpty)
Copy the code

We can also get the number of elements in the set:

print(setA.count)
Copy the code

The same is true for arrays, but the more general problem for collections is determining whether a collection contains an element. To do this, you can use the Contains method:

print(setA.contains("a"))
Copy the code

Add and remove elements from a collection

You can add and remove elements to mutable collections:

setD.insert("c")
setD.remove("a")
Copy the code

Because of the uniqueness of collection elements, the same element can only be added to the collection once. The INSERT method can be called multiple times with the same value, but the collection does not change.

var setE: Set = [1.2.3.4]
 
setE.insert(5)
setE.insert(5)
setE.insert(5)
 
print(setE) / /,5,1,2,3 [4]
Copy the code

As mentioned earlier, the above code may be output in a different order each time it executes because the collection elements are out of order.

Set to compare

It can be compared between sets. Obviously, two sets can be compared for equality:

letSetA: = (" a ", "b","c"]letSetB: = [" a ", "b","c"]if setA == setB {
     print(" the sets areequal")}Copy the code

In this case, the sets are equal.

Comparing the size of two sets is not clearly defined, but it is possible to check if one set is a subset of the other:

let intSetA: Set = [1.2.3.4.5.6.7.8.9.0]
let intSetB: Set = [1.2.3]
intSetB.isSubset(of: intSetA) //true
Copy the code

You can also check whether a set is a true subset of another set. This is the case where this set is a subset of another set but doesn’t want to wait.

let intSetA: Set = [1.2.3.4.5.6.7.8.9.0]
let intSetB: Set = [1.2.3.4.5.6.7.8.9.0]
let intSetC: Set = [3.4.5]
 
intSetB.isSubset(of: intSetA) //true
intSetB.isStrictSubset(of: intSetA) //false
intSetC.isSubset(of: intSetA) // true
intSetC.isStrictSubset(of: intSetA) //true
Copy the code

The opposite concept is the superset:

let intSetA: Set = [1.2.3.4.5.6.7.8.9.0]
let intSetC: Set = [3.4.5]
intSetA.isSuperset(of: intSetC) //true
intSetA.isStrictSuperset(of: intSetC) //true
Copy the code

If two sets do not have the same elements, they are said to be disjoint

let intSetA: Set = [1.2.3.4.5.6.7.8.9.0]
let intSetC: Set = [3.4.5]
let intSetD: Set = [13.14.15]
 
intSetA.isDisjoint(with: intSetC) //false
intSetA.isDisjoint(with: intSetD) //true
Copy the code

Set in combination with

You can combine two sets into a new set that contains all the elements of both sets:

let stringSetA: Set = ["a"."b"."c"]
let stringSetB: Set = ["c"."d"."e"]

let unionSetAB = stringSetA.union(stringSetB)
print(unionSetAB) //["d", "b", "c", "a", "e"]
Copy the code

An intersection, on the other hand, contains only elements common to two sets:

let stringSetA: Set = ["a"."b"."c"]
let stringSetB: Set = ["c"."d"."e"]
 
let intersectionAB = stringSetA.intersection(stringSetB)
print(intersectionAB) / / / "c"
Copy the code

Custom collection element types

You can store custom types in collections. This type can be a class or a structure. In order for collections to work properly, the type must comply with the Hashable protocol.

class Movie: Hashable {
 
     var title: String
     var year: Int
 
     init(title: String, year: Int) {
          self.title = title
          self.year = year
     }
 
     static func= =(lhs: Movie, rhs: Movie) -> Bool {
          return lhs.title == rhs.title &&
          lhs.year == rhs.year
     }
 
     var hashValue: Int {
          return title.hashValue ^ year.hashValue
     }
 
}
 
let terminator = Movie(title: "Terminator", year: 1980)
let backToTheFuture = Movie(title: "Back to the Future", year: 1985)
 
let movieSetA: Set = [terminator,backToTheFuture]
Copy the code

This article is translated by SwiftGG translation team and has been authorized to be translated by the authors. Please visit swift.gg for the latest articles.