OptionSet

protocol OptionSet

A type that presents a mathematical set interface to a bit set.

You use the OptionSet protocol to represent bitset types, where individual bits represent members of a set. Adopting this protocol in your custom types lets you perform set-related operations such as membership tests, unions, and intersections on those types. What's more, when implemented using specific criteria, adoption of this protocol requires no extra work on your part.

When creating an option set, include a rawValue property in your type declaration. The rawValue property must be of a type that conforms to the FixedWidthInteger protocol, such as Int or UInt8. Next, create unique options as static properties of your custom type using unique powers of two (1, 2, 4, 8, 16, and so forth) for each individual property's raw value so that each property can be represented by a single bit of the type's raw value.

For example, consider a custom type called ShippingOptions that is an option set of the possible ways to ship a customer's purchase. ShippingOptions includes a rawValue property of type Int that stores the bit mask of available shipping options. The static members nextDay, secondDay, priority, and standard are unique, individual options.

struct ShippingOptions: OptionSet {
    let rawValue: Int

    static let nextDay    = ShippingOptions(rawValue: 1 << 0)
    static let secondDay  = ShippingOptions(rawValue: 1 << 1)
    static let priority   = ShippingOptions(rawValue: 1 << 2)
    static let standard   = ShippingOptions(rawValue: 1 << 3)

    static let express: ShippingOptions = [.nextDay, .secondDay]
    static let all: ShippingOptions = [.express, .priority, .standard]
}

Declare additional preconfigured option set values as static properties initialized with an array literal containing other option values. In the example, because the express static property is assigned an array literal with the nextDay and secondDay options, it will contain those two elements.

Using an Option Set Type

When you need to create an instance of an option set, assign one of the type's static members to your variable or constant. Alternatively, to create an option set instance with multiple members, assign an array literal with multiple static members of the option set. To create an empty instance, assign an empty array literal to your variable.

let singleOption: ShippingOptions = .priority
let multipleOptions: ShippingOptions = [.nextDay, .secondDay, .priority]
let noOptions: ShippingOptions = []

Use set-related operations to check for membership and to add or remove members from an instance of your custom option set type. The following example shows how you can determine free shipping options based on a customer's purchase price:

let purchasePrice = 87.55

var freeOptions: ShippingOptions = []
if purchasePrice > 50 {
    freeOptions.insert(.priority)
}

if freeOptions.contains(.priority) {
    print("You've earned free priority shipping!")
} else {
    print("Add more to your cart for free priority shipping!")
}
// Prints "You've earned free priority shipping!"
Inheritance Equatable, ExpressibleByArrayLiteral, RawRepresentable, SetAlgebra View Protocol Hierarchy →
Associated Types
Element = Self

The element type of the option set.

To inherit all the default implementations from the OptionSet protocol, the Element type must be Self, the default.

ArrayLiteralElement

The type of the elements of an array literal.

RawValue

The raw type that can be used to represent all values of the conforming type.

Every distinct value of the conforming type has a corresponding unique value of the RawValue type, but there may be values of the RawValue type that don't have a corresponding value of the conforming type.

Import import Swift

Initializers

init(rawValue:) Required

Creates a new option set from the given raw value.

This initializer always succeeds, even if the value passed as rawValue exceeds the static properties declared as part of the option set. This example creates an instance of ShippingOptions with a raw value beyond the highest element, with a bit mask that effectively contains all the declared static members.

let extraOptions = ShippingOptions(rawValue: 255)
print(extraOptions.isStrictSuperset(of: .all))
// Prints "true"

rawValue: The raw value of the option set to create. Each bit of rawValue potentially represents an element of the option set, though raw values may include bits that are not defined as distinct values of the OptionSet type.

Declaration

init(rawValue: Self.RawValue)

Declared In

OptionSet , RawRepresentable
init(arrayLiteral:) Required

Creates an instance initialized with the given elements.

Declaration

init(arrayLiteral elements: Self.ArrayLiteralElement...)

Declared In

ExpressibleByArrayLiteral
init() Required

Creates an empty set.

This initializer is equivalent to initializing with an empty array literal. For example, you create an empty Set instance with either this initializer or with an empty array literal.

var emptySet = Set<Int>()
print(emptySet.isEmpty)
// Prints "true"

emptySet = []
print(emptySet.isEmpty)
// Prints "true"

Declaration

init()

Declared In

SetAlgebra
init(_:)

Creates a new set from a finite sequence of items.

Use this initializer to create a new set from an existing sequence, like an array or a range:

let validIndices = Set(0..<7).subtracting([2, 4, 5])
print(validIndices)
// Prints "[6, 0, 1, 3]"

sequence: The elements to use as members of the new set.

Declaration

init<S>(_ sequence: S)

Declared In

SetAlgebra

Instance Variables

var rawValue: Self.RawValue Required

The corresponding value of the raw type.

A new instance initialized with rawValue will be equivalent to this instance. For example:

enum PaperSize: String {
    case A4, A5, Letter, Legal
}

let selectedSize = PaperSize.Letter
print(selectedSize.rawValue)
// Prints "Letter"

print(selectedSize == PaperSize(rawValue: selectedSize.rawValue)!)
// Prints "true"

Declaration

var rawValue: Self.RawValue { get }

Declared In

RawRepresentable
var isEmpty: Bool

A Boolean value that indicates whether the set has no elements.

Declaration

var isEmpty: Bool { get }

Declared In

SetAlgebra

Instance Methods

func ==(_:rhs:) Required

Returns a Boolean value indicating whether two values are equal.

Equality is the inverse of inequality. For any values a and b, a == b implies that a != b is false.

Parameters: lhs: A value to compare. rhs: Another value to compare.

Declaration

func ==(lhs: Self, rhs: Self) -> Bool

Declared In

Equatable
func contains(_:) Required

Returns a Boolean value that indicates whether the given element exists in the set.

This example uses the contains(_:) method to test whether an integer is a member of a set of prime numbers.

let primes: Set = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
let x = 5
if primes.contains(x) {
    print("\(x) is prime!")
} else {
    print("\(x). Not prime.")
}
// Prints "5 is prime!"

member: An element to look for in the set. Returns: true if member exists in the set; otherwise, false.

Declaration

func contains(_ member: Self.Element) -> Bool

Declared In

SetAlgebra
mutating func formIntersection(_:) Required

Removes the elements of this set that aren't also in the given set.

In the following example, the elements of the employees set that are not also members of the neighbors set are removed. In particular, the names "Alicia", "Chris", and "Diana" are removed.

var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
employees.formIntersection(neighbors)
print(employees)
// Prints "["Bethany", "Eric"]"

other: A set of the same type as the current set.

Declaration

mutating func formIntersection(_ other: Self)

Declared In

SetAlgebra
mutating func formSymmetricDifference(_:) Required

Removes the elements of the set that are also in the given set and adds the members of the given set that are not already in the set.

In the following example, the elements of the employees set that are also members of neighbors are removed from employees, while the elements of neighbors that are not members of employees are added to employees. In particular, the names "Bethany" and "Eric" are removed from employees while the name "Forlani" is added.

var employees: Set = ["Alicia", "Bethany", "Diana", "Eric"]
let neighbors: Set = ["Bethany", "Eric", "Forlani"]
employees.formSymmetricDifference(neighbors)
print(employees)
// Prints "["Diana", "Forlani", "Alicia"]"

other: A set of the same type.

Declaration

mutating func formSymmetricDifference(_ other: Self)

Declared In

SetAlgebra
mutating func formUnion(_:) Required

Adds the elements of the given set to the set.

In the following example, the elements of the visitors set are added to the attendees set:

var attendees: Set = ["Alicia", "Bethany", "Diana"]
let visitors: Set = ["Diana", "Marcia", "Nathaniel"]
attendees.formUnion(visitors)
print(attendees)
// Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"

If the set already contains one or more elements that are also in other, the existing members are kept.

var initialIndices = Set(0..<5)
initialIndices.formUnion([2, 3, 6, 7])
print(initialIndices)
// Prints "[2, 4, 6, 7, 0, 1, 3]"

other: A set of the same type as the current set.

Declaration

mutating func formUnion(_ other: Self)

Declared In

SetAlgebra
mutating func insert(_:) Required

Inserts the given element in the set if it is not already present.

If an element equal to newMember is already contained in the set, this method has no effect. In this example, a new element is inserted into classDays, a set of days of the week. When an existing element is inserted, the classDays set does not change.

enum DayOfTheWeek: Int {
    case sunday, monday, tuesday, wednesday, thursday,
        friday, saturday
}

var classDays: Set<DayOfTheWeek> = [.wednesday, .friday]
print(classDays.insert(.monday))
// Prints "(true, .monday)"
print(classDays)
// Prints "[.friday, .wednesday, .monday]"

print(classDays.insert(.friday))
// Prints "(false, .friday)"
print(classDays)
// Prints "[.friday, .wednesday, .monday]"

newMember: An element to insert into the set. Returns: (true, newMember) if newMember was not contained in the set. If an element equal to newMember was already contained in the set, the method returns (false, oldMember), where oldMember is the element that was equal to newMember. In some cases, oldMember may be distinguishable from newMember by identity comparison or some other means.

Declaration

mutating func insert(_ newMember: Self.Element) -> (inserted: Bool, memberAfterInsert: Self.Element)

Declared In

SetAlgebra
func intersection(_:)

Returns a new set with the elements that are common to both this set and the given set.

In the following example, the bothNeighborsAndEmployees set is made up of the elements that are in both the employees and neighbors sets. Elements that are in only one or the other are left out of the result of the intersection.

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
let bothNeighborsAndEmployees = employees.intersection(neighbors)
print(bothNeighborsAndEmployees)
// Prints "["Bethany", "Eric"]"

other: A set of the same type as the current set. Returns: A new set.

Note: if this set and other contain elements that are equal but distinguishable (e.g. via ===), which of these elements is present in the result is unspecified.

Declaration

func intersection(_ other: Self) -> Self

Declared In

SetAlgebra
func isDisjoint(with:)

Returns a Boolean value that indicates whether the set has no members in common with the given set.

In the following example, the employees set is disjoint with the visitors set because no name appears in both sets.

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let visitors: Set = ["Marcia", "Nathaniel", "Olivia"]
print(employees.isDisjoint(with: visitors))
// Prints "true"

other: A set of the same type as the current set. Returns: true if the set has no elements in common with other; otherwise, false.

Declaration

func isDisjoint(with other: Self) -> Bool

Declared In

SetAlgebra
func isSubset(of:)

Returns a Boolean value that indicates whether the set is a subset of another set.

Set A is a subset of another set B if every member of A is also a member of B.

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let attendees: Set = ["Alicia", "Bethany", "Diana"]
print(attendees.isSubset(of: employees))
// Prints "true"

other: A set of the same type as the current set. Returns: true if the set is a subset of other; otherwise, false.

Declaration

func isSubset(of other: Self) -> Bool

Declared In

SetAlgebra
func isSuperset(of:)

Returns a Boolean value that indicates whether the set is a superset of the given set.

Set A is a superset of another set B if every member of B is also a member of A.

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let attendees: Set = ["Alicia", "Bethany", "Diana"]
print(employees.isSuperset(of: attendees))
// Prints "true"

other: A set of the same type as the current set. Returns: true if the set is a superset of possibleSubset; otherwise, false.

Declaration

func isSuperset(of other: Self) -> Bool

Declared In

SetAlgebra
mutating func remove(_:) Required

Removes the given element and any elements subsumed by the given element.

member: The element of the set to remove. Returns: For ordinary sets, an element equal to member if member is contained in the set; otherwise, nil. In some cases, a returned element may be distinguishable from newMember by identity comparison or some other means.

For sets where the set type and element type are the same, like OptionSet types, this method returns any intersection between the set and [member], or nil if the intersection is empty.

Declaration

mutating func remove(_ member: Self.Element) -> Self.Element?

Declared In

SetAlgebra
mutating func subtract(_:)

Removes the elements of the given set from this set.

In the following example, the elements of the employees set that are also members of the neighbors set are removed. In particular, the names "Bethany" and "Eric" are removed from employees.

var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
employees.subtract(neighbors)
print(employees)
// Prints "["Diana", "Chris", "Alicia"]"

other: A set of the same type as the current set.

Declaration

mutating func subtract(_ other: Self)

Declared In

SetAlgebra
func subtracting(_:)

Returns a new set containing the elements of this set that do not occur in the given set.

In the following example, the nonNeighbors set is made up of the elements of the employees set that are not elements of neighbors:

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
let nonNeighbors = employees.subtracting(neighbors)
print(nonNeighbors)
// Prints "["Diana", "Chris", "Alicia"]"

other: A set of the same type as the current set. Returns: A new set.

Declaration

func subtracting(_ other: Self) -> Self

Declared In

SetAlgebra
func symmetricDifference(_:)

Returns a new set with the elements that are either in this set or in the given set, but not in both.

In the following example, the eitherNeighborsOrEmployees set is made up of the elements of the employees and neighbors sets that are not in both employees and neighbors. In particular, the names "Bethany" and "Eric" do not appear in eitherNeighborsOrEmployees.

let employees: Set = ["Alicia", "Bethany", "Diana", "Eric"]
let neighbors: Set = ["Bethany", "Eric", "Forlani"]
let eitherNeighborsOrEmployees = employees.symmetricDifference(neighbors)
print(eitherNeighborsOrEmployees)
// Prints "["Diana", "Forlani", "Alicia"]"

other: A set of the same type as the current set. Returns: A new set.

Declaration

func symmetricDifference(_ other: Self) -> Self

Declared In

SetAlgebra
func union(_:)

Returns a new set with the elements of both this and the given set.

In the following example, the attendeesAndVisitors set is made up of the elements of the attendees and visitors sets:

let attendees: Set = ["Alicia", "Bethany", "Diana"]
let visitors = ["Marcia", "Nathaniel"]
let attendeesAndVisitors = attendees.union(visitors)
print(attendeesAndVisitors)
// Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"

If the set already contains one or more elements that are also in other, the existing members are kept.

let initialIndices = Set(0..<5)
let expandedIndices = initialIndices.union([2, 3, 6, 7])
print(expandedIndices)
// Prints "[2, 4, 6, 7, 0, 1, 3]"

other: A set of the same type as the current set. Returns: A new set with the unique elements of this set and other.

Note: if this set and other contain elements that are equal but distinguishable (e.g. via ===), which of these elements is present in the result is unspecified.

Declaration

func union(_ other: Self) -> Self

Declared In

SetAlgebra
mutating func update(with:) Required

Inserts the given element into the set unconditionally.

If an element equal to newMember is already contained in the set, newMember replaces the existing element. In this example, an existing element is inserted into classDays, a set of days of the week.

enum DayOfTheWeek: Int {
    case sunday, monday, tuesday, wednesday, thursday,
        friday, saturday
}

var classDays: Set<DayOfTheWeek> = [.monday, .wednesday, .friday]
print(classDays.update(with: .monday))
// Prints "Optional(.monday)"

newMember: An element to insert into the set. Returns: For ordinary sets, an element equal to newMember if the set already contained such a member; otherwise, nil. In some cases, the returned element may be distinguishable from newMember by identity comparison or some other means.

For sets where the set type and element type are the same, like OptionSet types, this method returns any intersection between the set and [newMember], or nil if the intersection is empty.

Declaration

mutating func update(with newMember: Self.Element) -> Self.Element?

Declared In

SetAlgebra

Default Implementations

init(_:)

Creates a new set from a finite sequence of items.

Use this initializer to create a new set from an existing sequence, like an array or a range:

let validIndices = Set(0..<7).subtracting([2, 4, 5])
print(validIndices)
// Prints "[6, 0, 1, 3]"

sequence: The elements to use as members of the new set.

Declaration

init<S>(_ sequence: S)

Declared In

SetAlgebra
var isEmpty: Bool

A Boolean value that indicates whether the set has no elements.

Declaration

var isEmpty: Bool { get }

Declared In

SetAlgebra
func !=(_:rhs:)

Returns a Boolean value indicating whether two values are not equal.

Inequality is the inverse of equality. For any values a and b, a != b implies that a == b is false.

This is the default implementation of the not-equal-to operator (!=) for any type that conforms to Equatable.

Parameters: lhs: A value to compare. rhs: Another value to compare.

Declaration

func !=(lhs: Self, rhs: Self) -> Bool

Declared In

Equatable
func intersection(_:)

Returns a new option set with only the elements contained in both this set and the given set.

This example uses the intersection(_:) method to limit the available shipping options to what can be used with a PO Box destination.

// Can only ship standard or priority to PO Boxes
let poboxShipping: ShippingOptions = [.standard, .priority]
let memberShipping: ShippingOptions =
        [.standard, .priority, .secondDay]

let availableOptions = memberShipping.intersection(poboxShipping)
print(availableOptions.contains(.priority))
// Prints "true"
print(availableOptions.contains(.secondDay))
// Prints "false"

other: An option set. Returns: A new option set with only the elements contained in both this set and other.

Declaration

func intersection(_ other: Self) -> Self
func isDisjoint(with:)

Returns a Boolean value that indicates whether the set has no members in common with the given set.

In the following example, the employees set is disjoint with the visitors set because no name appears in both sets.

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let visitors: Set = ["Marcia", "Nathaniel", "Olivia"]
print(employees.isDisjoint(with: visitors))
// Prints "true"

other: A set of the same type as the current set. Returns: true if the set has no elements in common with other; otherwise, false.

Declaration

func isDisjoint(with other: Self) -> Bool

Declared In

SetAlgebra
func isStrictSubset(of:)

Returns a Boolean value that indicates whether this set is a strict subset of the given set.

Set A is a strict subset of another set B if every member of A is also a member of B and B contains at least one element that is not a member of A.

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let attendees: Set = ["Alicia", "Bethany", "Diana"]
print(attendees.isStrictSubset(of: employees))
// Prints "true"

// A set is never a strict subset of itself:
print(attendees.isStrictSubset(of: attendees))
// Prints "false"

other: A set of the same type as the current set. Returns: true if the set is a strict subset of other; otherwise, false.

Declaration

func isStrictSubset(of other: Self) -> Bool

Declared In

SetAlgebra
func isStrictSuperset(of:)

Returns a Boolean value that indicates whether this set is a strict superset of the given set.

Set A is a strict superset of another set B if every member of B is also a member of A and A contains at least one element that is not a member of B.

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let attendees: Set = ["Alicia", "Bethany", "Diana"]
print(employees.isStrictSuperset(of: attendees))
// Prints "true"

// A set is never a strict superset of itself:
print(employees.isStrictSuperset(of: employees))
// Prints "false"

other: A set of the same type as the current set. Returns: true if the set is a strict superset of other; otherwise, false.

Declaration

func isStrictSuperset(of other: Self) -> Bool

Declared In

SetAlgebra
func isSubset(of:)

Returns a Boolean value that indicates whether the set is a subset of another set.

Set A is a subset of another set B if every member of A is also a member of B.

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let attendees: Set = ["Alicia", "Bethany", "Diana"]
print(attendees.isSubset(of: employees))
// Prints "true"

other: A set of the same type as the current set. Returns: true if the set is a subset of other; otherwise, false.

Declaration

func isSubset(of other: Self) -> Bool

Declared In

SetAlgebra
func isSuperset(of:)

Returns a Boolean value that indicates whether the set is a superset of the given set.

Set A is a superset of another set B if every member of B is also a member of A.

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let attendees: Set = ["Alicia", "Bethany", "Diana"]
print(employees.isSuperset(of: attendees))
// Prints "true"

other: A set of the same type as the current set. Returns: true if the set is a superset of other; otherwise, false.

Declaration

func isSuperset(of other: Self) -> Bool

Declared In

SetAlgebra
mutating func subtract(_:)

Removes the elements of the given set from this set.

In the following example, the elements of the employees set that are also members of the neighbors set are removed. In particular, the names "Bethany" and "Eric" are removed from employees.

var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
employees.subtract(neighbors)
print(employees)
// Prints "["Diana", "Chris", "Alicia"]"

other: A set of the same type as the current set.

Declaration

mutating func subtract(_ other: Self)

Declared In

SetAlgebra
func subtracting(_:)

Returns a new set containing the elements of this set that do not occur in the given set.

In the following example, the nonNeighbors set is made up of the elements of the employees set that are not elements of neighbors:

let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
let nonNeighbors = employees.subtract(neighbors)
print(nonNeighbors)
// Prints "["Diana", "Chris", "Alicia"]"

other: A set of the same type as the current set. Returns: A new set.

Declaration

func subtracting(_ other: Self) -> Self

Declared In

SetAlgebra
func symmetricDifference(_:)

Returns a new option set with the elements contained in this set or in the given set, but not in both.

other: An option set. Returns: A new option set with only the elements contained in either this set or other, but not in both.

Declaration

func symmetricDifference(_ other: Self) -> Self
func union(_:)

Returns a new option set of the elements contained in this set, in the given set, or in both.

This example uses the union(_:) method to add two more shipping options to the default set.

let defaultShipping = ShippingOptions.standard
let memberShipping = defaultShipping.union([.secondDay, .priority])
print(memberShipping.contains(.priority))
// Prints "true"

other: An option set. Returns: A new option set made up of the elements contained in this set, in other, or in both.

Declaration

func union(_ other: Self) -> Self

Where ArrayLiteralElement == Element

init(arrayLiteral:)

Creates a set containing the elements of the given array literal.

Do not call this initializer directly. It is used by the compiler when you use an array literal. Instead, create a new set using an array literal as its value by enclosing a comma-separated list of values in square brackets. You can use an array literal anywhere a set is expected by the type context.

Here, a set of strings is created from an array literal holding only strings:

let ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]
if ingredients.isSuperset(of: ["sugar", "salt"]) {
    print("Whatever it is, it's bound to be delicious!")
}
// Prints "Whatever it is, it's bound to be delicious!"

arrayLiteral: A list of elements of the new set.

Declaration

init(arrayLiteral: Self.Element...)

Declared In

SetAlgebra

Where RawValue : FixedWidthInteger

init()

Creates an empty option set.

This initializer creates an option set with a raw value of zero.

Declaration

init()
mutating func formIntersection(_:)

Removes all elements of this option set that are not also present in the given set.

This method is implemented as a & (bitwise AND) operation on the two sets' raw values.

other: An option set.

Declaration

mutating func formIntersection(_ other: Self)
mutating func formSymmetricDifference(_:)

Replaces this set with a new set containing all elements contained in either this set or the given set, but not in both.

This method is implemented as a ^ (bitwise XOR) operation on the two sets' raw values.

other: An option set.

Declaration

mutating func formSymmetricDifference(_ other: Self)
mutating func formUnion(_:)

Inserts the elements of another set into this option set.

This method is implemented as a | (bitwise OR) operation on the two sets' raw values.

other: An option set.

Declaration

mutating func formUnion(_ other: Self)

Where RawValue == Bool

init(from:)

Creates a new instance by decoding from the given decoder, when the type's RawValue is Bool.

This initializer throws an error if reading from the decoder fails, or if the data read is corrupted or otherwise invalid.

decoder: The decoder to read data from.

Declaration

init(from decoder: Decoder)

Declared In

RawRepresentable
func encode(to:)

Encodes this value into the given encoder, when the type's RawValue is Bool.

This function throws an error if any values are invalid for the given encoder's format.

encoder: The encoder to write data to.

Declaration

func encode(to encoder: Encoder) throws

Declared In

RawRepresentable

Where RawValue == Double

init(from:)

Creates a new instance by decoding from the given decoder, when the type's RawValue is Double.

This initializer throws an error if reading from the decoder fails, or if the data read is corrupted or otherwise invalid.

decoder: The decoder to read data from.

Declaration

init(from decoder: Decoder)

Declared In

RawRepresentable
func encode(to:)

Encodes this value into the given encoder, when the type's RawValue is Double.

This function throws an error if any values are invalid for the given encoder's format.

encoder: The encoder to write data to.

Declaration

func encode(to encoder: Encoder) throws

Declared In

RawRepresentable

Where RawValue == Float

init(from:)

Creates a new instance by decoding from the given decoder, when the type's RawValue is Float.

This initializer throws an error if reading from the decoder fails, or if the data read is corrupted or otherwise invalid.

decoder: The decoder to read data from.

Declaration

init(from decoder: Decoder)

Declared In

RawRepresentable
func encode(to:)

Encodes this value into the given encoder, when the type's RawValue is Float.

This function throws an error if any values are invalid for the given encoder's format.

encoder: The encoder to write data to.

Declaration

func encode(to encoder: Encoder) throws

Declared In

RawRepresentable

Where RawValue == Int

init(from:)

Creates a new instance by decoding from the given decoder, when the type's RawValue is Int.

This initializer throws an error if reading from the decoder fails, or if the data read is corrupted or otherwise invalid.

decoder: The decoder to read data from.

Declaration

init(from decoder: Decoder)

Declared In

RawRepresentable
func encode(to:)

Encodes this value into the given encoder, when the type's RawValue is Int.

This function throws an error if any values are invalid for the given encoder's format.

encoder: The encoder to write data to.

Declaration

func encode(to encoder: Encoder) throws

Declared In

RawRepresentable

Where RawValue == Int16

init(from:)

Creates a new instance by decoding from the given decoder, when the type's RawValue is Int16.

This initializer throws an error if reading from the decoder fails, or if the data read is corrupted or otherwise invalid.

decoder: The decoder to read data from.

Declaration

init(from decoder: Decoder)

Declared In

RawRepresentable
func encode(to:)

Encodes this value into the given encoder, when the type's RawValue is Int16.

This function throws an error if any values are invalid for the given encoder's format.

encoder: The encoder to write data to.

Declaration

func encode(to encoder: Encoder) throws

Declared In

RawRepresentable

Where RawValue == Int32

init(from:)

Creates a new instance by decoding from the given decoder, when the type's RawValue is Int32.

This initializer throws an error if reading from the decoder fails, or if the data read is corrupted or otherwise invalid.

decoder: The decoder to read data from.

Declaration

init(from decoder: Decoder)

Declared In

RawRepresentable
func encode(to:)

Encodes this value into the given encoder, when the type's RawValue is Int32.

This function throws an error if any values are invalid for the given encoder's format.

encoder: The encoder to write data to.

Declaration

func encode(to encoder: Encoder) throws

Declared In

RawRepresentable

Where RawValue == Int64

init(from:)

Creates a new instance by decoding from the given decoder, when the type's RawValue is Int64.

This initializer throws an error if reading from the decoder fails, or if the data read is corrupted or otherwise invalid.

decoder: The decoder to read data from.

Declaration

init(from decoder: Decoder)

Declared In

RawRepresentable
func encode(to:)

Encodes this value into the given encoder, when the type's RawValue is Int64.

This function throws an error if any values are invalid for the given encoder's format.

encoder: The encoder to write data to.

Declaration

func encode(to encoder: Encoder) throws

Declared In

RawRepresentable

Where RawValue == Int8

init(from:)

Creates a new instance by decoding from the given decoder, when the type's RawValue is Int8.

This initializer throws an error if reading from the decoder fails, or if the data read is corrupted or otherwise invalid.

decoder: The decoder to read data from.

Declaration

init(from decoder: Decoder)

Declared In

RawRepresentable
func encode(to:)

Encodes this value into the given encoder, when the type's RawValue is Int8.

This function throws an error if any values are invalid for the given encoder's format.

encoder: The encoder to write data to.

Declaration

func encode(to encoder: Encoder) throws

Declared In

RawRepresentable

Where RawValue == String

init(from:)

Creates a new instance by decoding from the given decoder, when the type's RawValue is String.

This initializer throws an error if reading from the decoder fails, or if the data read is corrupted or otherwise invalid.

decoder: The decoder to read data from.

Declaration

init(from decoder: Decoder)

Declared In

RawRepresentable
func encode(to:)

Encodes this value into the given encoder, when the type's RawValue is String.

This function throws an error if any values are invalid for the given encoder's format.

encoder: The encoder to write data to.

Declaration

func encode(to encoder: Encoder) throws

Declared In

RawRepresentable

Where RawValue == UInt

init(from:)

Creates a new instance by decoding from the given decoder, when the type's RawValue is UInt.

This initializer throws an error if reading from the decoder fails, or if the data read is corrupted or otherwise invalid.

decoder: The decoder to read data from.

Declaration

init(from decoder: Decoder)

Declared In

RawRepresentable
func encode(to:)

Encodes this value into the given encoder, when the type's RawValue is UInt.

This function throws an error if any values are invalid for the given encoder's format.

encoder: The encoder to write data to.

Declaration

func encode(to encoder: Encoder) throws

Declared In

RawRepresentable

Where RawValue == UInt16

init(from:)

Creates a new instance by decoding from the given decoder, when the type's RawValue is UInt16.

This initializer throws an error if reading from the decoder fails, or if the data read is corrupted or otherwise invalid.

decoder: The decoder to read data from.

Declaration

init(from decoder: Decoder)

Declared In

RawRepresentable
func encode(to:)

Encodes this value into the given encoder, when the type's RawValue is UInt16.

This function throws an error if any values are invalid for the given encoder's format.

encoder: The encoder to write data to.

Declaration

func encode(to encoder: Encoder) throws

Declared In

RawRepresentable

Where RawValue == UInt32

init(from:)

Creates a new instance by decoding from the given decoder, when the type's RawValue is UInt32.

This initializer throws an error if reading from the decoder fails, or if the data read is corrupted or otherwise invalid.

decoder: The decoder to read data from.

Declaration

init(from decoder: Decoder)

Declared In

RawRepresentable
func encode(to:)

Encodes this value into the given encoder, when the type's RawValue is UInt32.

This function throws an error if any values are invalid for the given encoder's format.

encoder: The encoder to write data to.

Declaration

func encode(to encoder: Encoder) throws

Declared In

RawRepresentable

Where RawValue == UInt64

init(from:)

Creates a new instance by decoding from the given decoder, when the type's RawValue is UInt64.

This initializer throws an error if reading from the decoder fails, or if the data read is corrupted or otherwise invalid.

decoder: The decoder to read data from.

Declaration

init(from decoder: Decoder)

Declared In

RawRepresentable
func encode(to:)

Encodes this value into the given encoder, when the type's RawValue is UInt64.

This function throws an error if any values are invalid for the given encoder's format.

encoder: The encoder to write data to.

Declaration

func encode(to encoder: Encoder) throws

Declared In

RawRepresentable

Where RawValue == UInt8

init(from:)

Creates a new instance by decoding from the given decoder, when the type's RawValue is UInt8.

This initializer throws an error if reading from the decoder fails, or if the data read is corrupted or otherwise invalid.

decoder: The decoder to read data from.

Declaration

init(from decoder: Decoder)

Declared In

RawRepresentable
func encode(to:)

Encodes this value into the given encoder, when the type's RawValue is UInt8.

This function throws an error if any values are invalid for the given encoder's format.

encoder: The encoder to write data to.

Declaration

func encode(to encoder: Encoder) throws

Declared In

RawRepresentable

Where Self == Element

func contains(_:)

Returns a Boolean value that indicates whether a given element is a member of the option set.

This example uses the contains(_:) method to check whether next-day shipping is in the availableOptions instance.

let availableOptions = ShippingOptions.express
if availableOptions.contains(.nextDay) {
    print("Next day shipping available")
}
// Prints "Next day shipping available"

member: The element to look for in the option set. Returns: true if the option set contains member; otherwise, false.

Declaration

func contains(_ member: Self) -> Bool
mutating func insert(_:)

Adds the given element to the option set if it is not already a member.

In the following example, the .secondDay shipping option is added to the freeOptions option set if purchasePrice is greater than 50.0. For the ShippingOptions declaration, see the OptionSet protocol discussion.

let purchasePrice = 87.55

var freeOptions: ShippingOptions = [.standard, .priority]
if purchasePrice > 50 {
    freeOptions.insert(.secondDay)
}
print(freeOptions.contains(.secondDay))
// Prints "true"

newMember: The element to insert. Returns: (true, newMember) if newMember was not contained in self. Otherwise, returns (false, oldMember), where oldMember is the member of the set equal to newMember.

Declaration

mutating func insert(_ newMember: Self.Element) -> (inserted: Bool, memberAfterInsert: Self.Element)
mutating func remove(_:)

Removes the given element and all elements subsumed by it.

In the following example, the .priority shipping option is removed from the options option set. Attempting to remove the same shipping option a second time results in nil, because options no longer contains .priority as a member.

var options: ShippingOptions = [.secondDay, .priority]
let priorityOption = options.remove(.priority)
print(priorityOption == .priority)
// Prints "true"

print(options.remove(.priority))
// Prints "nil"

In the next example, the .express element is passed to remove(_:). Although .express is not a member of options, .express subsumes the remaining .secondDay element of the option set. Therefore, options is emptied and the intersection between .express and options is returned.

let expressOption = options.remove(.express)
print(expressOption == .express)
// Prints "false"
print(expressOption == .secondDay)
// Prints "true"

member: The element of the set to remove. Returns: The intersection of [member] and the set, if the intersection was nonempty; otherwise, nil.

Declaration

mutating func remove(_ member: Self.Element) -> Self.Element?
mutating func update(with:)

Inserts the given element into the set.

If newMember is not contained in the set but subsumes current members of the set, the subsumed members are returned.

var options: ShippingOptions = [.secondDay, .priority]
let replaced = options.update(with: .express)
print(replaced == .secondDay)
// Prints "true"

Returns: The intersection of [newMember] and the set if the intersection was nonempty; otherwise, nil.

Declaration

mutating func update(with newMember: Self.Element) -> Self.Element?