🅿️OptionSet
struct ShippingOptions: OptionSet {
// ⭐️ required property
let rawValue: Int // ⭐️ conforms to 🅿️ FixedWidthInteger
}
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 = []
⭐️ 注意:OptionSet 的 methods 雖然看起來像是元素與集合間的用語 (源自於 SetAlgebra),但要注意每個 OptionSet 的 static properties 本質上還是一個「集合」的概念,就算只包含一個元素都是如此!
var A: ShippingOptions = []
let B: ShippingOptions = .priority
// ⭐️ 雖然以下是集合與元素間的用語,但 A 跟 B 其實都是集合喔!
A.insert(B)
A.contains(B)
Last updated
Was this helpful?