A type that provides mathematical set operations.
SDK
- Xcode 8.0+
Framework
- Swift Standard Library
Declaration
Overview
You use types that conform to the Set
protocol when you need efficient membership tests or mathematical set operations such as intersection, union, and subtraction. In the standard library, you can use the Set
type with elements of any hashable type, or you can easily create bit masks with Set
conformance using the Option
protocol. See those types for more information.
Note
Unlike ordinary set types, the Element
type of an Option
is identical to the Option
type itself. The Set
protocol is specifically designed to accommodate both kinds of set.
Conforming to the SetAlgebra Protocol
When implementing a custom type that conforms to the Set
protocol, you must implement the required initializers and methods. For the inherited methods to work properly, conforming types must meet the following axioms. Assume that S
is a custom type that conforms to the Set
protocol, x
and y
are instances of S
, and e
is of type S
—the type that the set holds.
S() == []
x
.intersection(x) == x x
.intersection([]) == [] x
.union(x) == x x
.union([]) == x x
implies.contains(e) x
.union(y).contains(e) x
implies.union(y).contains(e) x
.contains(e) || y .contains(e) x
if and only if.contains(e) && y .contains(e) x
.intersection(y).contains(e) x
implies.is Subset(of: y) x
.union(y) == y x
implies.is Superset(of: y) x
.union(y) == x x
if and only if.is Subset(of: y) y
.is Superset(of: x) x
if and only if.is Strict Superset(of: y) x
.is Superset(of: y) && x != y x
if and only if.is Strict Subset(of: y) x
.is Subset(of: y) && x != y