When creating an option set, include a rawValue property in your type declaration. For your type to automatically receive default implementations for set-related operations, the rawValueproperty must be of a type that conforms to the FixedWidthInteger protocol, such as Intor UInt8.
struct ShippingOptions: OptionSet {
// ⭐️ required property
let rawValue: Int // ⭐️ conforms to 🅿️ FixedWidthInteger
}
Next, create unique options as static properties of your custom type using unique powers of two (1, 2, 4, 8, 16 ...) for each individual property’s raw value so that each property can be represented by a single bit of the type’s raw value.
struct ShippingOptions: OptionSet {
let rawValue: Int
// ⭐️ unit sets (containing only one element)
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)
// ⭐️ useful sets (containing multiple elements)
// ⭐️ can be initialized by array literal (ExpressibleByArrayLiteral)
static let express: ShippingOptions = [.nextDay, .secondDay]
static let all: ShippingOptions = [.express, .priority, .standard]
}
// ⭐️ empty set
let noOptions: ShippingOptions = []
var A: ShippingOptions = []
let B: ShippingOptions = .priority
// ⭐️ 雖然以下是集合與元素間的用語,但 A 跟 B 其實都是集合喔!
A.insert(B)
A.contains(B)