Grant Emerson

No Sweat for OptionSet

No Sweat for OptionSet β€” SwiftMoji Entry #5

OptionSet is a protocol in Swift that provides a way to efficiently combine a group of related values into a set using an underlying bitmask β€” a group of bits (0s and 1s) that can be programmatically switched on and off using bitwise operations. OptionSet conforms to SetAlgebra and can therefore be declared with the Array Literal syntax (e.g. [.x, .y]). A struct can conform to OptionSet by providing a rawValue property along with a group of static constant instances of the conforming type. The bitwise left shift operator (<<) is used to assign each instance to a unique rawValue with a single bit. For example, 1 << 4 is 0b10000 in binary and has only one bit-value turned on. The usage of single bits for expressing membership makes storing OptionSets very efficient. For example, a set of πŸŽ’Items containing a πŸ’», πŸ““, and πŸ“· would be represented as a single binary integer 0b00111 in memory. OptionSets also work with common set operations such as union(_:) which allows for static constant sets to be melded together.

struct πŸŽ’Items: OptionSet {
    let rawValue: Int
    
    static let πŸ’» = πŸŽ’Items(rawValue: 1 << 0)
    static let πŸ““ = πŸŽ’Items(rawValue: 1 << 1)
    static let πŸ“· = πŸŽ’Items(rawValue: 1 << 2)
    static let πŸ”¦ = πŸŽ’Items(rawValue: 1 << 3)
    static let 🍎 = πŸŽ’Items(rawValue: 1 << 4)
    
    static let school: πŸŽ’Items = [.πŸ’», .πŸ““]
    static let hike: πŸŽ’Items = [.πŸ”¦, .🍎]
    static let all: πŸŽ’Items = [.πŸ’», .πŸ““, .πŸ“·, .πŸ”¦, .🍎]
}

struct πŸŽ’ {
    enum Color {
        case black, white, red
    }
    
    var color: Color
    var items: πŸŽ’Items
}

var fieldTripπŸŽ’ = πŸŽ’(color: .red, items: πŸŽ’Items.school.union(.hike))
Tagged with: