A type that can be converted to and from an associated raw value.
- Xcode 6.0.1+
Raw type, you can switch back and forth between a custom type and an associated
Raw type without losing the value of the original
Raw type. Using the raw value of a conforming type streamlines interoperation with Objective-C and legacy APIs and simplifies conformance to other protocols, such as
Raw protocol is seen mainly in two categories of types: enumerations with raw value types and option sets.
Enumerations with Raw Values
For any enumeration with a string, integer, or floating-point raw type, the Swift compiler automatically adds
Raw conformance. When defining your own custom enumeration, you give it a raw type by specifying the raw type as the first item in the enumeration’s type inheritance list. You can also use literals to specify values for one or more cases.
For example, the
Counter enumeration defined here has an
Int raw value type and gives the first case a raw value of
You can create a
Counter instance from an integer value between 1 and 5 by using the
init?(raw initializer declared in the
Raw protocol. This initializer is failable because although every case of the
Counter type has a corresponding
Int value, there are many
Int values that don’t correspond to a case of
Option sets all conform to
Raw by inheritance using the
Option protocol. Whether using an option set or creating your own, you use the raw value of an option set instance to store the instance’s bitfield. The raw value must therefore be of a type that conforms to the
Bitwise protocol, such as
Int. For example, the
Direction type defines an option set for the four directions you can move in a game.
Unlike enumerations, option sets provide a nonfailable
init(raw initializer to convert from a raw value, because option sets don’t have an enumerated list of all possible cases. Option set values have a one-to-one correspondence with their associated raw values.
In the case of the
Directions option set, an instance can contain zero, one, or more of the four defined directions. This example declares a constant with three currently allowed moves. The raw value of the
allowed instance is the result of the bitwise OR of its three members’ raw values:
Option sets use bitwise operations on their associated raw values to implement their mathematical set operations. For example, the
contains() method on
allowed performs a bitwise AND operation to check whether the option set contains an element.