No Sweat for OptionSet
Published on Dec 5, 2019No 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: