Tuesday, October 4, 2016

Option Sets in Swift

Ole Begemann:

Swift imports this definition not as an enum, but as a struct that conforms to the OptionSet protocol. Why a struct and not an enum? Enums are great when the cases are mutually exclusive, i.e. only one option can be set at a time. But you can’t combine multiple enum cases into a single value in Swift — unlike in C, where an enum is treated like an integer by the compiler and can assume any value.

An option set struct uses the same efficient representation as a bit field in C, but it presents itself externally as a set whose members are the selected options. This allows you to manipulate the bit field with standard set operations, such as testing for membership with contains or combining two bit fields with union. And because OptionSet inherits from ExpressibleByArrayLiteral, you can populate an option set with an array literal[…]

Comments RSS · Twitter

Leave a Comment