An integer type that uses a fixed size for every instance.
- Xcode 9.0+
- Swift Standard Library
Fixed protocol adds binary bitwise operations, bit shifts, and overflow handling to the operations supported by the
Fixed protocol as a constraint or extension point when writing operations that depend on bit shifting, performing bitwise operations, catching overflows, or having access to the maximum or minimum representable value of a type. For example, the following code provides a
binary property on every fixed-width integer that represents the number’s binary representation, split into 8-bit chunks.
binary implementation uses the static
bit property and the right shift operator (
>>), both of which are available to any type that conforms to the
The next example declares a generic
squared function, which accepts an instance
x of any fixed-width integer type. The function uses the
multiplied method to multiply
x by itself and check whether the result is too large to represent in the same type.
Conforming to the FixedWidthInteger Protocol
To make your own custom type conform to the
Fixed protocol, declare the required initializers, properties, and methods. The required methods that are suffixed with
Reporting serve as the customization points for arithmetic operations. When you provide just those methods, the standard library provides default implementations for all other arithmetic methods and operators.