- Mastering macOS Programming
- Stuart Grimshaw
- 150字
- 2021-07-02 22:54:16
Sets
Set objects are like an unordered Array in which any given value can only be present once.
Their declaration looks as follows:
let set1: Set = [1, 2]
Note that the Set literal looks like an Array, and so the type must be set explicitly.
The most common Set methods are probably the following:
var set1: Set = ["a", "b"]
let elementPresent = set1.contains("a") // true
let (added1, element1) = set1.insert("c") // (true, "c")
let (added2, element2) = set1.insert("c") // (false, "c")
let removedElement1 = set1.remove("a") // "a"
let removedElement2 = set1.remove("x") // nil
Inserting an object that is already in the set leaves the set unaltered, but note that the insert method also returns a tuple containing a Bool of whether the element was added, as well as the element itself.
The remove method returns the object--removed if it was present, or nil if it was not.