OptionSet
如果變數的行為像「單選題」,可考慮用 enum。
如果類似「多選題」,可考慮用 OptionSet。
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 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 ...) for each individual property’s raw value so that each property can be represented by a single bit of the type’s raw value.
⭐️ 注意:OptionSet 的 methods 雖然看起來像是元素與集合間的用語 (源自於 SetAlgebra),但要注意每個 OptionSet 的 static properties 本質上還是一個「集合」的概念,就算只包含一個元素都是如此!
Last updated
Was this helpful?