๐Ÿ…ฟ๏ธ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 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 = []

โญ๏ธ ๆณจๆ„๏ผšOptionSet ็š„ methods ้›–็„ถ็œ‹่ตทไพ†ๅƒๆ˜ฏๅ…ƒ็ด ่ˆ‡้›†ๅˆ้–“็š„็”จ่ชž (ๆบ่‡ชๆ–ผ SetAlgebra)๏ผŒไฝ†่ฆๆณจๆ„ๆฏๅ€‹ OptionSet ็š„ static properties ๆœฌ่ณชไธŠ้‚„ๆ˜ฏไธ€ๅ€‹ใ€Œ้›†ๅˆใ€็š„ๆฆ‚ๅฟต๏ผŒๅฐฑ็ฎ—ๅชๅŒ…ๅซไธ€ๅ€‹ๅ…ƒ็ด ้ƒฝๆ˜ฏๅฆ‚ๆญค๏ผ

var A: ShippingOptions = []
let B: ShippingOptions = .priority

// โญ๏ธ ้›–็„ถไปฅไธ‹ๆ˜ฏ้›†ๅˆ่ˆ‡ๅ…ƒ็ด ้–“็š„็”จ่ชž๏ผŒไฝ† A ่ทŸ B ๅ…ถๅฏฆ้ƒฝๆ˜ฏ้›†ๅˆๅ–”๏ผ
A.insert(B)
A.contains(B)

Last updated