protocol FixedWidthInteger
Inheritance |
BinaryInteger, Comparable, CustomStringConvertible, Equatable, ExpressibleByIntegerLiteral, Hashable, LosslessStringConvertible, Numeric, Strideable, _BitwiseOperations
View Protocol Hierarchy →
|
---|---|
Associated Types |
Words : Sequence
A type that represents the words of a binary integer. The IntegerLiteralType : _ExpressibleByBuiltinIntegerLiteral
A type that represents an integer literal. The standard library integer and floating-point types are all valid types
for |
Import | import Swift |
Initializers
Creates an integer from its big-endian representation, changing the byte order if necessary.
value
: A value to use as the big-endian representation of the
new integer.
Declaration
init(bigEndian value: Self)
Creates an integer from its little-endian representation, changing the byte order if necessary.
value
: A value to use as the little-endian representation of
the new integer.
Declaration
init(littleEndian value: Self)
Creates an integer from the given floating-point value, rounding toward zero.
Any fractional part of the value passed as source
is removed, rounding
the value toward zero.
let x = Int(21.5)
// x == 21
let y = Int(-21.5)
// y == -21
If source
is outside the bounds of this type after rounding toward
zero, a runtime error may occur.
let z = UInt(-21.5)
// Error: ...the result would be less than UInt.min
source
: A floating-point value to convert to an integer.
source
must be representable in this type after rounding toward
zero.
Declaration
init<T>(_ source: T)
Declared In
BinaryInteger
Creates a new instance with the representable value that's closest to the given integer.
If the value passed as source
is greater than the maximum representable
value in this type, the result is the type's max
value. If source
is
less than the smallest representable value in this type, the result is
the type's min
value.
In this example, x
is initialized as an Int8
instance by clamping
500
to the range -128...127
, and y
is initialized as a UInt
instance by clamping -500
to the range 0...UInt.max
.
let x = Int8(clamping: 500)
// x == 127
// x == Int8.max
let y = UInt(clamping: -500)
// y == 0
source
: An integer to convert to this type.
Declaration
init<T>(clamping source: T)
Declared In
BinaryInteger
Creates a new instance from the bit pattern of the given instance by sign-extending or truncating to fit this type.
When the bit width of T
(the type of source
) is equal to or greater
than this type's bit width, the result is the truncated
least-significant bits of source
. For example, when converting a
16-bit value to an 8-bit type, only the lower 8 bits of source
are
used.
let p: Int16 = -500
// 'p' has a binary representation of 11111110_00001100
let q = Int8(truncatingIfNeeded: p)
// q == 12
// 'q' has a binary representation of 00001100
When the bit width of T
is less than this type's bit width, the result
is sign-extended to fill the remaining bits. That is, if source
is
negative, the result is padded with ones; otherwise, the result is
padded with zeros.
let u: Int8 = 21
// 'u' has a binary representation of 00010101
let v = Int16(truncatingIfNeeded: u)
// v == 21
// 'v' has a binary representation of 00000000_00010101
let w: Int8 = -21
// 'w' has a binary representation of 11101011
let x = Int16(truncatingIfNeeded: w)
// x == -21
// 'x' has a binary representation of 11111111_11101011
let y = UInt16(truncatingIfNeeded: w)
// y == 65515
// 'y' has a binary representation of 11111111_11101011
source
: An integer to convert to this type.
Declaration
init<T>(truncatingIfNeeded source: T)
Declared In
BinaryInteger
Creates an integer from the given floating-point value, if it can be represented exactly.
If the value passed as source
is not representable exactly, the result
is nil
. In the following example, the constant x
is successfully
created from a value of 21.0
, while the attempt to initialize the
constant y
from 21.5
fails:
let x = Int(exactly: 21.0)
// x == Optional(21)
let y = Int(exactly: 21.5)
// y == nil
source
: A floating-point value to convert to an integer.
Declaration
init?<T>(exactly source: T)
Declared In
BinaryInteger
, Numeric
Creates an instance initialized to the specified integer value.
Do not call this initializer directly. Instead, initialize a variable or constant using an integer literal. For example:
let x = 23
In this example, the assignment to the x
constant calls this integer
literal initializer behind the scenes.
value
: The value to create.
Declaration
init(integerLiteral value: Self.IntegerLiteralType)
Declared In
ExpressibleByIntegerLiteral
Instantiates an instance of the conforming type from a string representation.
Declaration
init?(_ description: String)
Declared In
LosslessStringConvertible
Static Variables
The number of bits used for the underlying binary representation of values of this type.
An unsigned, fixed-width integer type can represent values from 0 through
(2 ** bitWidth) - 1
, where **
is exponentiation. A signed,
fixed-width integer type can represent values from
-(2 ** (bitWidth - 1))
through (2 ** (bitWidth - 1)) - 1
. For example,
the Int8
type has a bitWidth
value of 8 and can store any integer in
the range -128...127
.
Declaration
static var bitWidth: Int { get }
The maximum representable integer in this type.
For unsigned integer types, this value is (2 ** bitWidth) - 1
, where
**
is exponentiation. For signed integer types, this value is
(2 ** (bitWidth - 1)) - 1
.
Declaration
static var max: Self { get }
The minimum representable integer in this type.
For unsigned integer types, this value is always 0
. For signed integer
types, this value is -(2 ** (bitWidth - 1))
, where **
is
exponentiation.
Declaration
static var min: Self { get }
A Boolean value indicating whether this type is a signed integer type.
Signed integer types can represent both positive and negative values. Unsigned integer types can represent only nonnegative values.
Declaration
static var isSigned: Bool { get }
Declared In
BinaryInteger
Instance Variables
The big-endian representation of this integer.
If necessary, the byte order of this value is reversed from the typical
byte order of this integer type. On a big-endian platform, for any
integer x
, x == x.bigEndian
.
Declaration
var bigEndian: Self { get }
A representation of this integer with the byte order swapped.
Declaration
var byteSwapped: Self { get }
The number of leading zeros in this value's binary representation.
For example, in a fixed-width integer type with a bitWidth
value of 8,
the number 31 has three leading zeros.
let x: Int8 = 0b0001_1111
// x == 31
// x.leadingZeroBitCount == 3
Declaration
var leadingZeroBitCount: Int { get }
The little-endian representation of this integer.
If necessary, the byte order of this value is reversed from the typical
byte order of this integer type. On a little-endian platform, for any
integer x
, x == x.littleEndian
.
Declaration
var littleEndian: Self { get }
The number of bits equal to 1 in this value's binary representation.
For example, in a fixed-width integer type with a bitWidth
value of 8,
the number 31 has five bits equal to 1.
let x: Int8 = 0b0001_1111
// x == 31
// x.nonzeroBitCount == 5
Declaration
var nonzeroBitCount: Int { get }
The number of trailing zeros in this value's binary representation.
For example, in a fixed-width integer type with a bitWidth
value of 8,
the number -8 has three trailing zeros.
let x = Int8(bitPattern: 0b1111_1000)
// x == -8
// x.trailingZeroBitCount == 3
Declaration
var trailingZeroBitCount: Int { get }
Declared In
BinaryInteger
A collection containing the words of this value's binary representation, in order from the least significant to most significant.
Negative values are returned in two's complement representation, regardless of the type's underlying implementation.
Declaration
var words: Self.Words { get }
Declared In
BinaryInteger
A textual representation of this instance.
Calling this property directly is discouraged. Instead, convert an
instance of any type to a string by using the String(describing:)
initializer. This initializer works with any type, and uses the custom
description
property for types that conform to
CustomStringConvertible
:
struct Point: CustomStringConvertible {
let x: Int, y: Int
var description: String {
return "(\(x), \(y))"
}
}
let p = Point(x: 21, y: 30)
let s = String(describing: p)
print(s)
// Prints "(21, 30)"
The conversion of p
to a string in the assignment to s
uses the
Point
type's description
property.
Declaration
var description: String { get }
Declared In
CustomStringConvertible
The hash value.
Hash values are not guaranteed to be equal across different executions of your program. Do not save hash values to use during a future execution.
Declaration
var hashValue: Int { get }
Declared In
Hashable
The magnitude of this value.
For any numeric value x
, x.magnitude
is the absolute value of x
.
You can use the magnitude
property in operations that are simpler to
implement in terms of unsigned values, such as printing the value of an
integer, which is just printing a '-' character in front of an absolute
value.
let x = -200
// x.magnitude == 200
The global abs(_:)
function provides more familiar syntax when you need
to find an absolute value. In addition, because abs(_:)
always returns
a value of the same type, even in a generic context, using the function
instead of the magnitude
property is encouraged.
Declaration
var magnitude: Self.Magnitude { get }
Declared In
Numeric
Instance Methods
Returns the remainder of dividing the first value by the second.
The result of the modulo operator (%
) has the same sign as lhs
and is
less than rhs.magnitude
.
let x = 22 % 5
// x == 2
let y = 22 % -5
// y == 2
let z = -22 % -5
// z == -2
For any two integers a
and b
, their quotient q
, and their remainder
r
, a == b * q + r
.
Parameters:
lhs: The value to divide.
rhs: The value to divide lhs
by. rhs
must not be zero.
Declaration
func %(lhs: Self, rhs: Self) -> Self
Declared In
BinaryInteger
Divides the first value by the second and stores the remainder in the left-hand-side variable.
The result has the same sign as lhs
and is less than rhs.magnitude
.
var x = 22
x %= 5
// x == 2
var y = 22
y %= -5
// y == 2
var z = -22
z %= -5
// z == -2
Parameters:
lhs: The value to divide.
rhs: The value to divide lhs
by. rhs
must not be zero.
Declaration
func %=(lhs: inout Self, rhs: Self)
Declared In
BinaryInteger
Returns the result of performing a bitwise AND operation on the two given values.
A bitwise AND operation results in a value that has each bit set to 1
where both of its arguments have that bit set to 1
. For example:
let x: UInt8 = 5 // 0b00000101
let y: UInt8 = 14 // 0b00001110
let z = x & y // 0b00000100
// z == 4
Parameters: lhs: An integer value. rhs: Another integer value.
Declaration
func &(lhs: Self, rhs: Self) -> Self
Declared In
BinaryInteger
Returns the result of shifting a value's binary representation the specified number of digits to the left, masking the shift amount to the type's bit width.
Use the masking left shift operator (&<<
) when you need to perform a
shift and are sure that the shift amount is in the range
0..<lhs.bitWidth
. Before shifting, the masking left shift operator
masks the shift to this range. The shift is performed using this masked
value.
The following example defines x
as an instance of UInt8
, an 8-bit,
unsigned integer type. If you use 2
as the right-hand-side value in an
operation on x
, the shift amount requires no masking.
let x: UInt8 = 30 // 0b00011110
let y = x &<< 2
// y == 120 // 0b01111000
However, if you use 8
as the shift amount, the method first masks the
shift amount to zero, and then performs the shift, resulting in no change
to the original value.
let z = x &<< 8
// z == 30 // 0b00011110
If the bit width of the shifted integer type is a power of two, masking is performed using a bitmask; otherwise, masking is performed using a modulo operation.
Parameters:
lhs: The value to shift.
rhs: The number of bits to shift lhs
to the left. If rhs
is
outside the range 0..<lhs.bitWidth
, it is masked to produce a
value within that range.
Declaration
func &<<(lhs: Self, rhs: Self) -> Self
Returns the result of shifting a value's binary representation the specified number of digits to the left, masking the shift amount to the type's bit width, and stores the result in the left-hand-side variable.
The &<<=
operator performs a masking shift, where the value used as
rhs
is masked to produce a value in the range 0..<lhs.bitWidth
. The
shift is performed using this masked value.
The following example defines x
as an instance of UInt8
, an 8-bit,
unsigned integer type. If you use 2
as the right-hand-side value in an
operation on x
, the shift amount requires no masking.
var x: UInt8 = 30 // 0b00011110
x &<<= 2
// x == 120 // 0b01111000
However, if you pass 19
as rhs
, the method first bitmasks rhs
to
3
, and then uses that masked value as the number of bits to shift lhs
.
var y: UInt8 = 30 // 0b00011110
y &<<= 19
// y == 240 // 0b11110000
Parameters:
lhs: The value to shift.
rhs: The number of bits to shift lhs
to the left. If rhs
is
outside the range 0..<lhs.bitWidth
, it is masked to produce a
value within that range.
Declaration
func &<<=(lhs: inout Self, rhs: Self)
Stores the result of performing a bitwise AND operation on the two given values in the left-hand-side variable.
A bitwise AND operation results in a value that has each bit set to 1
where both of its arguments have that bit set to 1
. For example:
var x: UInt8 = 5 // 0b00000101
let y: UInt8 = 14 // 0b00001110
x &= y // 0b00000100
Parameters: lhs: An integer value. rhs: Another integer value.
Declaration
func &=(lhs: inout Self, rhs: Self)
Declared In
BinaryInteger
Returns the result of shifting a value's binary representation the specified number of digits to the right, masking the shift amount to the type's bit width.
Use the masking right shift operator (&>>
) when you need to perform a
shift and are sure that the shift amount is in the range
0..<lhs.bitWidth
. Before shifting, the masking right shift operator
masks the shift to this range. The shift is performed using this masked
value.
The following example defines x
as an instance of UInt8
, an 8-bit,
unsigned integer type. If you use 2
as the right-hand-side value in an
operation on x
, the shift amount requires no masking.
let x: UInt8 = 30 // 0b00011110
let y = x &>> 2
// y == 7 // 0b00000111
However, if you use 8
as the shift amount, the method first masks the
shift amount to zero, and then performs the shift, resulting in no change
to the original value.
let z = x &>> 8
// z == 30 // 0b00011110
If the bit width of the shifted integer type is a power of two, masking is performed using a bitmask; otherwise, masking is performed using a modulo operation.
Parameters:
lhs: The value to shift.
rhs: The number of bits to shift lhs
to the right. If rhs
is
outside the range 0..<lhs.bitWidth
, it is masked to produce a
value within that range.
Declaration
func &>>(lhs: Self, rhs: Self) -> Self
Calculates the result of shifting a value's binary representation the specified number of digits to the right, masking the shift amount to the type's bit width, and stores the result in the left-hand-side variable.
The &>>=
operator performs a masking shift, where the value passed as
rhs
is masked to produce a value in the range 0..<lhs.bitWidth
. The
shift is performed using this masked value.
The following example defines x
as an instance of UInt8
, an 8-bit,
unsigned integer type. If you use 2
as the right-hand-side value in an
operation on x
, the shift amount requires no masking.
var x: UInt8 = 30 // 0b00011110
x &>>= 2
// x == 7 // 0b00000111
However, if you use 19
as rhs
, the operation first bitmasks rhs
to
3
, and then uses that masked value as the number of bits to shift lhs
.
var y: UInt8 = 30 // 0b00011110
y &>>= 19
// y == 3 // 0b00000011
Parameters:
lhs: The value to shift.
rhs: The number of bits to shift lhs
to the right. If rhs
is
outside the range 0..<lhs.bitWidth
, it is masked to produce a
value within that range.
Declaration
func &>>=(lhs: inout Self, rhs: Self)
Multiplies two values and produces their product.
The multiplication operator (*
) calculates the product of its two
arguments. For example:
2 * 3 // 6
100 * 21 // 2100
-10 * 15 // -150
3.5 * 2.25 // 7.875
You cannot use *
with arguments of different types. To multiply values
of different types, convert one of the values to the other value's type.
let x: Int8 = 21
let y: Int = 1000000
Int(x) * y // 21000000
Parameters: lhs: The first value to multiply. rhs: The second value to multiply.
Declaration
func *(lhs: Self, rhs: Self) -> Self
Declared In
BinaryInteger
, Numeric
Multiplies two values and stores the result in the left-hand-side variable.
Parameters: lhs: The first value to multiply. rhs: The second value to multiply.
Declaration
func *=(lhs: inout Self, rhs: Self)
Declared In
BinaryInteger
, Numeric
Adds two values and produces their sum.
The addition operator (+
) calculates the sum of its two arguments. For
example:
1 + 2 // 3
-10 + 15 // 5
-15 + -5 // -20
21.5 + 3.25 // 24.75
You cannot use +
with arguments of different types. To add values of
different types, convert one of the values to the other value's type.
let x: Int8 = 21
let y: Int = 1000000
Int(x) + y // 1000021
Parameters: lhs: The first value to add. rhs: The second value to add.
Declaration
func +(lhs: Self, rhs: Self) -> Self
Declared In
BinaryInteger
, Numeric
Adds two values and stores the result in the left-hand-side variable.
Parameters: lhs: The first value to add. rhs: The second value to add.
Declaration
func +=(lhs: inout Self, rhs: Self)
Declared In
BinaryInteger
, Numeric
Returns the quotient of dividing the first value by the second.
For integer types, any remainder of the division is discarded.
let x = 21 / 5
// x == 4
Parameters:
lhs: The value to divide.
rhs: The value to divide lhs
by. rhs
must not be zero.
Declaration
func /(lhs: Self, rhs: Self) -> Self
Declared In
BinaryInteger
Divides the first value by the second and stores the quotient in the left-hand-side variable.
For integer types, any remainder of the division is discarded.
var x = 21
x /= 5
// x == 4
Parameters:
lhs: The value to divide.
rhs: The value to divide lhs
by. rhs
must not be zero.
Declaration
func /=(lhs: inout Self, rhs: Self)
Declared In
BinaryInteger
Returns a Boolean value indicating whether the value of the first argument is less than that of the second argument.
This function is the only requirement of the Comparable
protocol. The
remainder of the relational operator functions are implemented by the
standard library for any type that conforms to Comparable
.
Parameters: lhs: A value to compare. rhs: Another value to compare.
Declaration
func <(lhs: Self, rhs: Self) -> Bool
Declared In
Comparable
Returns the result of shifting a value's binary representation the specified number of digits to the left.
The <<
operator performs a smart shift, which defines a result for a
shift of any value.
- Using a negative value for
rhs
performs a right shift usingabs(rhs)
. - Using a value for
rhs
that is greater than or equal to the bit width oflhs
is an overshift, resulting in zero. - Using any other value for
rhs
performs a left shift onlhs
by that amount.
The following example defines x
as an instance of UInt8
, an 8-bit,
unsigned integer type. If you use 2
as the right-hand-side value in an
operation on x
, the value is shifted left by two bits.
let x: UInt8 = 30 // 0b00011110
let y = x << 2
// y == 120 // 0b01111000
If you use 11
as rhs
, x
is overshifted such that all of its bits
are set to zero.
let z = x << 11
// z == 0 // 0b00000000
Using a negative value as rhs
is the same as performing a right shift
with abs(rhs)
.
let a = x << -3
// a == 3 // 0b00000011
let b = x >> 3
// b == 3 // 0b00000011
Parameters:
lhs: The value to shift.
rhs: The number of bits to shift lhs
to the left.
Declaration
func <<<RHS>(lhs: Self, rhs: RHS) -> Self where RHS : BinaryInteger
Declared In
BinaryInteger
Stores the result of shifting a value's binary representation the specified number of digits to the left in the left-hand-side variable.
The <<
operator performs a smart shift, which defines a result for a
shift of any value.
- Using a negative value for
rhs
performs a right shift usingabs(rhs)
. - Using a value for
rhs
that is greater than or equal to the bit width oflhs
is an overshift, resulting in zero. - Using any other value for
rhs
performs a left shift onlhs
by that amount.
The following example defines x
as an instance of UInt8
, an 8-bit,
unsigned integer type. If you use 2
as the right-hand-side value in an
operation on x
, the value is shifted left by two bits.
var x: UInt8 = 30 // 0b00011110
x <<= 2
// x == 120 // 0b01111000
If you use 11
as rhs
, x
is overshifted such that all of its bits
are set to zero.
var y: UInt8 = 30 // 0b00011110
y <<= 11
// y == 0 // 0b00000000
Using a negative value as rhs
is the same as performing a right shift
with abs(rhs)
.
var a: UInt8 = 30 // 0b00011110
a <<= -3
// a == 3 // 0b00000011
var b: UInt8 = 30 // 0b00011110
b >>= 3
// b == 3 // 0b00000011
Parameters:
lhs: The value to shift.
rhs: The number of bits to shift lhs
to the left.
Declaration
func <<=<RHS>(lhs: inout Self, rhs: RHS)
Declared In
BinaryInteger
Returns a Boolean value indicating whether the value of the first argument is less than or equal to that of the second argument.
Parameters: lhs: A value to compare. rhs: Another value to compare.
Declaration
func <=(lhs: Self, rhs: Self) -> Bool
Declared In
Comparable
Returns a Boolean value indicating whether two values are equal.
Equality is the inverse of inequality. For any values a
and b
,
a == b
implies that a != b
is false
.
Parameters: lhs: A value to compare. rhs: Another value to compare.
Declaration
func ==(lhs: Self, rhs: Self) -> Bool
Declared In
Equatable
Returns a Boolean value indicating whether the value of the first argument is greater than that of the second argument.
Parameters: lhs: A value to compare. rhs: Another value to compare.
Declaration
func >(lhs: Self, rhs: Self) -> Bool
Declared In
Comparable
Returns a Boolean value indicating whether the value of the first argument is greater than or equal to that of the second argument.
Parameters: lhs: A value to compare. rhs: Another value to compare.
Declaration
func >=(lhs: Self, rhs: Self) -> Bool
Declared In
Comparable
Returns the result of shifting a value's binary representation the specified number of digits to the right.
The >>
operator performs a smart shift, which defines a result for a
shift of any value.
- Using a negative value for
rhs
performs a left shift usingabs(rhs)
. - Using a value for
rhs
that is greater than or equal to the bit width oflhs
is an overshift. An overshift results in-1
for a negative value oflhs
or0
for a nonnegative value. - Using any other value for
rhs
performs a right shift onlhs
by that amount.
The following example defines x
as an instance of UInt8
, an 8-bit,
unsigned integer type. If you use 2
as the right-hand-side value in an
operation on x
, the value is shifted right by two bits.
let x: UInt8 = 30 // 0b00011110
let y = x >> 2
// y == 7 // 0b00000111
If you use 11
as rhs
, x
is overshifted such that all of its bits
are set to zero.
let z = x >> 11
// z == 0 // 0b00000000
Using a negative value as rhs
is the same as performing a left shift
using abs(rhs)
.
let a = x >> -3
// a == 240 // 0b11110000
let b = x << 3
// b == 240 // 0b11110000
Right shift operations on negative values "fill in" the high bits with ones instead of zeros.
let q: Int8 = -30 // 0b11100010
let r = q >> 2
// r == -8 // 0b11111000
let s = q >> 11
// s == -1 // 0b11111111
Parameters:
lhs: The value to shift.
rhs: The number of bits to shift lhs
to the right.
Declaration
func >><RHS>(lhs: Self, rhs: RHS) -> Self where RHS : BinaryInteger
Declared In
BinaryInteger
Stores the result of shifting a value's binary representation the specified number of digits to the right in the left-hand-side variable.
The >>=
operator performs a smart shift, which defines a result for a
shift of any value.
- Using a negative value for
rhs
performs a left shift usingabs(rhs)
. - Using a value for
rhs
that is greater than or equal to the bit width oflhs
is an overshift. An overshift results in-1
for a negative value oflhs
or0
for a nonnegative value. - Using any other value for
rhs
performs a right shift onlhs
by that amount.
The following example defines x
as an instance of UInt8
, an 8-bit,
unsigned integer type. If you use 2
as the right-hand-side value in an
operation on x
, the value is shifted right by two bits.
var x: UInt8 = 30 // 0b00011110
x >>= 2
// x == 7 // 0b00000111
If you use 11
as rhs
, x
is overshifted such that all of its bits
are set to zero.
var y: UInt8 = 30 // 0b00011110
y >>= 11
// y == 0 // 0b00000000
Using a negative value as rhs
is the same as performing a left shift
using abs(rhs)
.
var a: UInt8 = 30 // 0b00011110
a >>= -3
// a == 240 // 0b11110000
var b: UInt8 = 30 // 0b00011110
b <<= 3
// b == 240 // 0b11110000
Right shift operations on negative values "fill in" the high bits with ones instead of zeros.
var q: Int8 = -30 // 0b11100010
q >>= 2
// q == -8 // 0b11111000
var r: Int8 = -30 // 0b11100010
r >>= 11
// r == -1 // 0b11111111
Parameters:
lhs: The value to shift.
rhs: The number of bits to shift lhs
to the right.
Declaration
func >>=<RHS>(lhs: inout Self, rhs: RHS)
Declared In
BinaryInteger
Returns the result of performing a bitwise XOR operation on the two given values.
A bitwise XOR operation, also known as an exclusive OR operation, results
in a value that has each bit set to 1
where one or the other but not
both of its arguments had that bit set to 1
. For example:
let x: UInt8 = 5 // 0b00000101
let y: UInt8 = 14 // 0b00001110
let z = x ^ y // 0b00001011
// z == 11
Parameters: lhs: An integer value. rhs: Another integer value.
Declaration
func ^(lhs: Self, rhs: Self) -> Self
Declared In
BinaryInteger
Stores the result of performing a bitwise XOR operation on the two given values in the left-hand-side variable.
A bitwise XOR operation, also known as an exclusive OR operation, results
in a value that has each bit set to 1
where one or the other but not
both of its arguments had that bit set to 1
. For example:
var x: UInt8 = 5 // 0b00000101
let y: UInt8 = 14 // 0b00001110
x ^= y // 0b00001011
Parameters: lhs: An integer value. rhs: Another integer value.
Declaration
func ^=(lhs: inout Self, rhs: Self)
Declared In
BinaryInteger
Returns the result of performing a bitwise OR operation on the two given values.
A bitwise OR operation results in a value that has each bit set to 1
where one or both of its arguments have that bit set to 1
. For
example:
let x: UInt8 = 5 // 0b00000101
let y: UInt8 = 14 // 0b00001110
let z = x | y // 0b00001111
// z == 15
Parameters: lhs: An integer value. rhs: Another integer value.
Declaration
func |(lhs: Self, rhs: Self) -> Self
Declared In
BinaryInteger
Stores the result of performing a bitwise OR operation on the two given values in the left-hand-side variable.
A bitwise OR operation results in a value that has each bit set to 1
where one or both of its arguments have that bit set to 1
. For
example:
var x: UInt8 = 5 // 0b00000101
let y: UInt8 = 14 // 0b00001110
x |= y // 0b00001111
Parameters: lhs: An integer value. rhs: Another integer value.
Declaration
func |=(lhs: inout Self, rhs: Self)
Declared In
BinaryInteger
Returns the inverse of the bits set in the argument.
The bitwise NOT operator (~
) is a prefix operator that returns a value
in which all the bits of its argument are flipped: Bits that are 1
in
the argument are 0
in the result, and bits that are 0
in the argument
are 1
in the result. This is equivalent to the inverse of a set. For
example:
let x: UInt8 = 5 // 0b00000101
let notX = ~x // 0b11111010
Performing a bitwise NOT operation on 0 returns a value with every bit
set to 1
.
let allOnes = ~UInt8.min // 0b11111111
Complexity: O(1).
Declaration
prefix func ~(x: Self) -> Self
Declared In
BinaryInteger
Subtracts one value from another and produces their difference.
The subtraction operator (-
) calculates the difference of its two
arguments. For example:
8 - 3 // 5
-10 - 5 // -15
100 - -5 // 105
10.5 - 100.0 // -89.5
You cannot use -
with arguments of different types. To subtract values
of different types, convert one of the values to the other value's type.
let x: UInt8 = 21
let y: UInt = 1000000
y - UInt(x) // 999979
Parameters:
lhs: A numeric value.
rhs: The value to subtract from lhs
.
Declaration
func -(lhs: Self, rhs: Self) -> Self
Declared In
BinaryInteger
, Numeric
Subtracts the second value from the first and stores the difference in the left-hand-side variable.
Parameters:
lhs: A numeric value.
rhs: The value to subtract from lhs
.
Declaration
func -=(lhs: inout Self, rhs: Self)
Declared In
BinaryInteger
, Numeric
Returns the sum of this value and the given value, along with a Boolean value indicating whether overflow occurred in the operation.
rhs
: The value to add to this value.
Returns: A tuple containing the result of the addition along with a
Boolean value indicating whether overflow occurred. If the overflow
component is false
, the partialValue
component contains the entire
sum. If the overflow
component is true
, an overflow occurred and
the partialValue
component contains the truncated sum of this value
and rhs
.
Declaration
func addingReportingOverflow(_ rhs: Self) -> (partialValue: Self, overflow: Bool)
Returns a value that is offset the specified distance from this value.
Use the advanced(by:)
method in generic code to offset a value by a
specified distance. If you're working directly with numeric values, use
the addition operator (+
) instead of this method.
func addOne<T: Strideable>(to x: T) -> T
where T.Stride : ExpressibleByIntegerLiteral
{
return x.advanced(by: 1)
}
let x = addOne(to: 5)
// x == 6
let y = addOne(to: 3.5)
// y = 4.5
If this type's Stride
type conforms to BinaryInteger
, then for a
value x
, a distance n
, and a value y = x.advanced(by: n)
,
x.distance(to: y) == n
. Using this method with types that have a
noninteger Stride
may result in an approximation.
n
: The distance to advance this value.
Returns: A value that is offset from this value by n
.
Complexity: O(1)
Declaration
func advanced(by n: Self.Stride) -> Self
Declared In
Strideable
Returns the distance from this value to the given value, expressed as a stride.
If this type's Stride
type conforms to BinaryInteger
, then for two
values x
and y
, and a distance n = x.distance(to: y)
,
x.advanced(by: n) == y
. Using this method with types that have a
noninteger Stride
may result in an approximation.
other
: The value to calculate the distance to.
Returns: The distance from this value to other
.
Complexity: O(1)
Declaration
func distance(to other: Self) -> Self.Stride
Declared In
Strideable
Returns the quotient obtained by dividing this value by the given value, along with a Boolean value indicating whether overflow occurred in the operation.
Dividing by zero is not an error when using this method. For a value x
,
the result of x.dividedReportingOverflow(by: 0)
is (x, true)
.
rhs
: The value to divide this value by.
Returns: A tuple containing the result of the division along with a
Boolean value indicating whether overflow occurred. If the overflow
component is false
, the partialValue
component contains the entire
quotient. If the overflow
component is true
, an overflow occurred
and the partialValue
component contains either the truncated quotient
or, if the quotient is undefined, the dividend.
Declaration
func dividedReportingOverflow(by rhs: Self) -> (partialValue: Self, overflow: Bool)
Returns a tuple containing the quotient and remainder obtained by dividing the given value by this value.
The resulting quotient must be representable within the bounds of the type. If the quotient is too large to represent in the type, a runtime error may occur.
The following example divides a value that is too large to be represented
using a single Int
instance by another Int
value. Because the quotient
is representable as an Int
, the division succeeds.
// 'dividend' represents the value 0x506f70652053616e74612049494949
let dividend = (22640526660490081, 7959093232766896457 as UInt)
let divisor = 2241543570477705381
let (quotient, remainder) = divisor.dividingFullWidth(dividend)
// quotient == 186319822866995413
// remainder == 0
dividend
: A tuple containing the high and low parts of a
double-width integer.
Returns: A tuple containing the quotient and remainder obtained by
dividing dividend
by this value.
Declaration
func dividingFullWidth(_ dividend: (high: Self, low: Self.Magnitude)) -> (quotient: Self, remainder: Self)
Hashes the essential components of this value by feeding them into the given hasher.
Implement this method to conform to the Hashable
protocol. The
components used for hashing must be the same as the components compared
in your type's ==
operator implementation. Call hasher.combine(_:)
with each of these components.
Important: Never call finalize()
on hasher
. Doing so may become a
compile-time error in the future.
hasher
: The hasher to use when combining the components
of this instance.
Declaration
func hash(into hasher: inout Hasher)
Declared In
Hashable
Returns a tuple containing the high and low parts of the result of multiplying this value by the given value.
Use this method to calculate the full result of a product that would
otherwise overflow. Unlike traditional truncating multiplication, the
multipliedFullWidth(by:)
method returns a tuple containing both the
high
and low
parts of the product of this value and other
. The
following example uses this method to multiply two Int8
values that
normally overflow when multiplied:
let x: Int8 = 48
let y: Int8 = -40
let result = x.multipliedFullWidth(by: y)
// result.high == -8
// result.low == 128
The product of x
and y
is -1920
, which is too large to represent in
an Int8
instance. The high
and low
compnents of the result
value
represent -1920
when concatenated to form a double-width integer; that
is, using result.high
as the high byte and result.low
as the low byte
of an Int16
instance.
let z = Int16(result.high) << 8 | Int16(result.low)
// z == -1920
other
: The value to multiply this value by.
Returns: A tuple containing the high and low parts of the result of
multiplying this value and other
.
Declaration
func multipliedFullWidth(by other: Self) -> (high: Self, low: Self.Magnitude)
Returns the product of this value and the given value, along with a Boolean value indicating whether overflow occurred in the operation.
rhs
: The value to multiply by this value.
Returns: A tuple containing the result of the multiplication along with
a Boolean value indicating whether overflow occurred. If the overflow
component is false
, the partialValue
component contains the entire
product. If the overflow
component is true
, an overflow occurred and
the partialValue
component contains the truncated product of this
value and rhs
.
Declaration
func multipliedReportingOverflow(by rhs: Self) -> (partialValue: Self, overflow: Bool)
Returns the quotient and remainder of this value divided by the given value.
Use this method to calculate the quotient and remainder of a division at the same time.
let x = 1_000_000
let (q, r) = x.quotientAndRemainder(dividingBy: 933)
// q == 1071
// r == 757
rhs
: The value to divide this value by.
Returns: A tuple containing the quotient and remainder of this value
divided by rhs
.
Declaration
func quotientAndRemainder(dividingBy rhs: Self) -> (quotient: Self, remainder: Self)
Declared In
BinaryInteger
Returns the remainder after dividing this value by the given value, along with a Boolean value indicating whether overflow occurred during division.
Dividing by zero is not an error when using this method. For a value x
,
the result of x.remainderReportingOverflow(dividingBy: 0)
is
(x, true)
.
rhs
: The value to divide this value by.
Returns: A tuple containing the result of the operation along with a
Boolean value indicating whether overflow occurred. If the overflow
component is false
, the partialValue
component contains the entire
remainder. If the overflow
component is true
, an overflow occurred
during division and the partialValue
component contains either the
entire remainder or, if the remainder is undefined, the dividend.
Declaration
func remainderReportingOverflow(dividingBy rhs: Self) -> (partialValue: Self, overflow: Bool)
Returns -1
if this value is negative and 1
if it's positive;
otherwise, 0
.
Returns: The sign of this number, expressed as an integer of the same type.
Declaration
func signum() -> Self
Declared In
BinaryInteger
Returns the difference obtained by subtracting the given value from this value, along with a Boolean value indicating whether overflow occurred in the operation.
rhs
: The value to subtract from this value.
Returns: A tuple containing the result of the subtraction along with a
Boolean value indicating whether overflow occurred. If the overflow
component is false
, the partialValue
component contains the entire
difference. If the overflow
component is true
, an overflow occurred
and the partialValue
component contains the truncated result of rhs
subtracted from this value.
Declaration
func subtractingReportingOverflow(_ rhs: Self) -> (partialValue: Self, overflow: Bool)
Default Implementations
Creates an integer from the given floating-point value, rounding toward
zero. Any fractional part of the value passed as source
is removed.
let x = Int(21.5)
// x == 21
let y = Int(-21.5)
// y == -21
If source
is outside the bounds of this type after rounding toward
zero, a runtime error may occur.
let z = UInt(-21.5)
// Error: ...outside the representable range
source
: A floating-point value to convert to an integer.
source
must be representable in this type after rounding toward
zero.
Declaration
init<T>(_ source: T)
Creates an integer from its big-endian representation, changing the byte order if necessary.
value
: A value to use as the big-endian representation of the
new integer.
Declaration
init(bigEndian value: Self)
Creates a new instance with the representable value that's closest to the given integer.
If the value passed as source
is greater than the maximum representable
value in this type, the result is the type's max
value. If source
is
less than the smallest representable value in this type, the result is
the type's min
value.
In this example, x
is initialized as an Int8
instance by clamping
500
to the range -128...127
, and y
is initialized as a UInt
instance by clamping -500
to the range 0...UInt.max
.
let x = Int8(clamping: 500)
// x == 127
// x == Int8.max
let y = UInt(clamping: -500)
// y == 0
source
: An integer to convert to this type.
Declaration
init<Other>(clamping source: Other)
Creates an instance initialized to the specified integer value.
Do not call this initializer directly. Instead, initialize a variable or constant using an integer literal. For example:
let x = 23
In this example, the assignment to the x
constant calls this integer
literal initializer behind the scenes.
value
: The value to create.
Declaration
init(integerLiteral value: Self)
Declared In
BinaryInteger
Creates an integer from its little-endian representation, changing the byte order if necessary.
value
: A value to use as the little-endian representation of
the new integer.
Declaration
init(littleEndian value: Self)
Creates a new instance from the bit pattern of the given instance by truncating or sign-extending if needed to fit this type.
When the bit width of T
(the type of source
) is equal to or greater
than this type's bit width, the result is the truncated
least-significant bits of source
. For example, when converting a
16-bit value to an 8-bit type, only the lower 8 bits of source
are
used.
let p: Int16 = -500
// 'p' has a binary representation of 11111110_00001100
let q = Int8(truncatingIfNeeded: p)
// q == 12
// 'q' has a binary representation of 00001100
When the bit width of T
is less than this type's bit width, the result
is sign-extended to fill the remaining bits. That is, if source
is
negative, the result is padded with ones; otherwise, the result is
padded with zeros.
let u: Int8 = 21
// 'u' has a binary representation of 00010101
let v = Int16(truncatingIfNeeded: u)
// v == 21
// 'v' has a binary representation of 00000000_00010101
let w: Int8 = -21
// 'w' has a binary representation of 11101011
let x = Int16(truncatingIfNeeded: w)
// x == -21
// 'x' has a binary representation of 11111111_11101011
let y = UInt16(truncatingIfNeeded: w)
// y == 65515
// 'y' has a binary representation of 11111111_11101011
source
: An integer to convert to this type.
Declaration
init<T>(truncatingIfNeeded source: T)
Creates a new integer value from the given string.
The string passed as description
may begin with a plus or minus sign
character (+
or -
), followed by one or more numeric digits (0-9
).
let x = Int("123")
// x == 123
If description
is in an invalid format, or if the value it denotes in
base 10 is not representable, the result is nil
. For example, the
following conversions result in nil
:
Int(" 100") // Includes whitespace
Int("21-50") // Invalid format
Int("ff6600") // Characters out of bounds
Int("10000000000000000000000000") // Out of range
description
: The ASCII representation of a number.
Declaration
init?(_ description: String)
Creates a new integer value from the given string and radix.
The string passed as text
may begin with a plus or minus sign character
(+
or -
), followed by one or more numeric digits (0-9
) or letters
(a-z
or A-Z
). Parsing of the string is case insensitive.
let x = Int("123")
// x == 123
let y = Int("-123", radix: 8)
// y == -83
let y = Int("+123", radix: 8)
// y == +83
let z = Int("07b", radix: 16)
// z == 123
If text
is in an invalid format or contains characters that are out of
bounds for the given radix
, or if the value it denotes in the given
radix
is not representable, the result is nil
. For example, the
following conversions result in nil
:
Int(" 100") // Includes whitespace
Int("21-50") // Invalid format
Int("ff6600") // Characters out of bounds
Int("zzzzzzzzzzzzz", radix: 36) // Out of range
Parameters:
text: The ASCII representation of a number in the radix passed as
radix
.
radix: The radix, or base, to use for converting text
to an integer
value. radix
must be in the range 2...36
. The default is 10.
Declaration
init?<S>(_ text: S, radix: Int = default)
Creates an integer from the given floating-point value, if it can be represented exactly.
If the value passed as source
is not representable exactly, the result
is nil
. In the following example, the constant x
is successfully
created from a value of 21.0
, while the attempt to initialize the
constant y
from 21.5
fails:
let x = Int(exactly: 21.0)
// x == Optional(21)
let y = Int(exactly: 21.5)
// y == nil
source
: A floating-point value to convert to an integer.
Declaration
init?<T>(exactly source: T)
The big-endian representation of this integer.
If necessary, the byte order of this value is reversed from the typical
byte order of this integer type. On a big-endian platform, for any
integer x
, x == x.bigEndian
.
Declaration
var bigEndian: Self { get }
The number of bits in the binary representation of this value.
Declaration
var bitWidth: Int { get }
A textual representation of this value.
Declaration
var description: String { get }
Declared In
BinaryInteger
The little-endian representation of this integer.
If necessary, the byte order of this value is reversed from the typical
byte order of this integer type. On a little-endian platform, for any
integer x
, x == x.littleEndian
.
Declaration
var littleEndian: Self { get }
Returns a Boolean value indicating whether two values are not equal.
Inequality is the inverse of equality. For any values a
and b
, a != b
implies that a == b
is false
.
This is the default implementation of the not-equal-to operator (!=
)
for any type that conforms to Equatable
.
Parameters: lhs: A value to compare. rhs: Another value to compare.
Declaration
func !=(lhs: Self, rhs: Self) -> Bool
Declared In
BinaryInteger
Returns a Boolean value indicating whether the two given values are not equal.
You can check the inequality of instances of any BinaryInteger
types
using the not-equal-to operator (!=
). For example, you can test
whether the first UInt8
value in a string's UTF-8 encoding is not
equal to the first UInt32
value in its Unicode scalar view:
let gameName = "Red Light, Green Light"
if let firstUTF8 = gameName.utf8.first,
let firstScalar = gameName.unicodeScalars.first?.value {
print("First code values are different: \(firstUTF8 != firstScalar)")
}
// Prints "First code values are different: false"
Parameters: lhs: An integer to compare. rhs: Another integer to compare.
Declaration
func !=<Other>(lhs: Self, rhs: Other) -> Bool where Other : BinaryInteger
Declared In
BinaryInteger
Returns the result of performing a bitwise AND operation on the two given values.
A bitwise AND operation results in a value that has each bit set to 1
where both of its arguments have that bit set to 1
. For example:
let x: UInt8 = 5 // 0b00000101
let y: UInt8 = 14 // 0b00001110
let z = x & y // 0b00000100
// z == 4
Parameters: lhs: An integer value. rhs: Another integer value.
Declaration
func &(lhs: Self, rhs: Self) -> Self
Declared In
BinaryInteger
Returns the product of the two given values, discarding any overflow.
The masking multiplication operator (&*
) silently discards any overflow
that occurs during the operation. In the following example, the product
of 10
and 50
is greater than the maximum representable Int8
value,
so the result is the overflowed value:
let x: Int8 = 10 &* 5
// x == 50
let y: Int8 = 10 &* 50
// y == -12 (after overflow)
Parameters: lhs: The first value to multiply. rhs: The second value to multiply.
Declaration
func &*(lhs: Self, rhs: Self) -> Self
Multiplies two values and stores the result in the left-hand-side variable, discarding any overflow.
The masking multiplication assignment operator (&*=
) silently discards
any overflow that occurs during the operation. In the following example,
the product of 10
and 50
is greater than the maximum representable
Int8
value, so the result is the overflowed value:
var x: Int8 = 10
x &*= 5
// x == 50
var y: Int8 = 10
y &*= 50
// y == -12 (after overflow)
Parameters: lhs: The first value to multiply. rhs: The second value to multiply.
Declaration
func &*=(lhs: inout Self, rhs: Self)
Returns the sum of the two given values, discarding any overflow.
The masking addition operator (&+
) silently discards any overflow that
occurs during the operation. In the following example, the sum of 100
and 121
is greater than the maximum representable Int8
value, so the
result is the overflowed value:
let x: Int8 = 10 &+ 21
// x == 31
let y: Int8 = 100 &+ 121
// y == -35 (after overflow)
Parameters: lhs: The first value to add. rhs: The second value to add.
Declaration
func &+(lhs: Self, rhs: Self) -> Self
Adds two values and stores the result in the left-hand-side variable, discarding any overflow.
The masking addition assignment operator (&+=
) silently discards any
overflow that occurs during the operation. In the following example, the
sum of 100
and 121
is greater than the maximum representable Int8
value, so the result is the overflowed value:
var x: Int8 = 10
x &+= 21
// x == 31
var y: Int8 = 100
y &+= 121
// y == -35 (after overflow)
Parameters: lhs: The first value to add. rhs: The second value to add.
Declaration
func &+=(lhs: inout Self, rhs: Self)
Returns the result of shifting a value's binary representation the specified number of digits to the left, masking the shift amount to the type's bit width.
Use the masking left shift operator (&<<
) when you need to perform a
shift and are sure that the shift amount is in the range
0..<lhs.bitWidth
. Before shifting, the masking left shift operator
masks the shift to this range. The shift is performed using this masked
value.
The following example defines x
as an instance of UInt8
, an 8-bit,
unsigned integer type. If you use 2
as the right-hand-side value in an
operation on x
, the shift amount requires no masking.
let x: UInt8 = 30 // 0b00011110
let y = x &<< 2
// y == 120 // 0b01111000
However, if you use 8
as the shift amount, the method first masks the
shift amount to zero, and then performs the shift, resulting in no change
to the original value.
let z = x &<< 8
// z == 30 // 0b00011110
If the bit width of the shifted integer type is a power of two, masking is performed using a bitmask; otherwise, masking is performed using a modulo operation.
Parameters:
lhs: The value to shift.
rhs: The number of bits to shift lhs
to the left. If rhs
is
outside the range 0..<lhs.bitWidth
, it is masked to produce a
value within that range.
Declaration
func &<<(lhs: Self, rhs: Self) -> Self
Returns the result of shifting a value's binary representation the specified number of digits to the left, masking the shift amount to the type's bit width.
Use the masking left shift operator (&<<
) when you need to perform a
shift and are sure that the shift amount is in the range
0..<lhs.bitWidth
. Before shifting, the masking left shift operator
masks the shift to this range. The shift is performed using this masked
value.
The following example defines x
as an instance of UInt8
, an 8-bit,
unsigned integer type. If you use 2
as the right-hand-side value in an
operation on x
, the shift amount requires no masking.
let x: UInt8 = 30 // 0b00011110
let y = x &<< 2
// y == 120 // 0b01111000
However, if you use 8
as the shift amount, the method first masks the
shift amount to zero, and then performs the shift, resulting in no change
to the original value.
let z = x &<< 8
// z == 30 // 0b00011110
If the bit width of the shifted integer type is a power of two, masking is performed using a bitmask; otherwise, masking is performed using a modulo operation.
Parameters:
lhs: The value to shift.
rhs: The number of bits to shift lhs
to the left. If rhs
is
outside the range 0..<lhs.bitWidth
, it is masked to produce a
value within that range.
Declaration
func &<<<Other>(lhs: Self, rhs: Other) -> Self where Other : BinaryInteger
Returns the result of shifting a value's binary representation the specified number of digits to the left, masking the shift amount to the type's bit width, and stores the result in the left-hand-side variable.
The &<<=
operator performs a masking shift, where the value used as
rhs
is masked to produce a value in the range 0..<lhs.bitWidth
. The
shift is performed using this masked value.
The following example defines x
as an instance of UInt8
, an 8-bit,
unsigned integer type. If you use 2
as the right-hand-side value in an
operation on x
, the shift amount requires no masking.
var x: UInt8 = 30 // 0b00011110
x &<<= 2
// x == 120 // 0b01111000
However, if you pass 19
as rhs
, the method first bitmasks rhs
to
3
, and then uses that masked value as the number of bits to shift lhs
.
var y: UInt8 = 30 // 0b00011110
y &<<= 19
// y == 240 // 0b11110000
Parameters:
lhs: The value to shift.
rhs: The number of bits to shift lhs
to the left. If rhs
is
outside the range 0..<lhs.bitWidth
, it is masked to produce a
value within that range.
Declaration
func &<<=<Other>(lhs: inout Self, rhs: Other)
Returns the result of shifting a value's binary representation the specified number of digits to the right, masking the shift amount to the type's bit width.
Use the masking right shift operator (&>>
) when you need to perform a
shift and are sure that the shift amount is in the range
0..<lhs.bitWidth
. Before shifting, the masking right shift operator
masks the shift to this range. The shift is performed using this masked
value.
The following example defines x
as an instance of UInt8
, an 8-bit,
unsigned integer type. If you use 2
as the right-hand-side value in an
operation on x
, the shift amount requires no masking.
let x: UInt8 = 30 // 0b00011110
let y = x &>> 2
// y == 7 // 0b00000111
However, if you use 8
as the shift amount, the method first masks the
shift amount to zero, and then performs the shift, resulting in no change
to the original value.
let z = x &>> 8
// z == 30 // 0b00011110
If the bit width of the shifted integer type is a power of two, masking is performed using a bitmask; otherwise, masking is performed using a modulo operation.
Parameters:
lhs: The value to shift.
rhs: The number of bits to shift lhs
to the right. If rhs
is
outside the range 0..<lhs.bitWidth
, it is masked to produce a
value within that range.
Declaration
func &>>(lhs: Self, rhs: Self) -> Self
Returns the result of shifting a value's binary representation the specified number of digits to the right, masking the shift amount to the type's bit width.
Use the masking right shift operator (&>>
) when you need to perform a
shift and are sure that the shift amount is in the range
0..<lhs.bitWidth
. Before shifting, the masking right shift operator
masks the shift to this range. The shift is performed using this masked
value.
The following example defines x
as an instance of UInt8
, an 8-bit,
unsigned integer type. If you use 2
as the right-hand-side value in an
operation on x
, the shift amount requires no masking.
let x: UInt8 = 30 // 0b00011110
let y = x &>> 2
// y == 7 // 0b00000111
However, if you use 8
as the shift amount, the method first masks the
shift amount to zero, and then performs the shift, resulting in no change
to the original value.
let z = x &>> 8
// z == 30 // 0b00011110
If the bit width of the shifted integer type is a power of two, masking is performed using a bitmask; otherwise, masking is performed using a modulo operation.
Parameters:
lhs: The value to shift.
rhs: The number of bits to shift lhs
to the right. If rhs
is
outside the range 0..<lhs.bitWidth
, it is masked to produce a
value within that range.
Declaration
func &>><Other>(lhs: Self, rhs: Other) -> Self where Other : BinaryInteger
Calculates the result of shifting a value's binary representation the specified number of digits to the right, masking the shift amount to the type's bit width, and stores the result in the left-hand-side variable.
The &>>=
operator performs a masking shift, where the value passed as
rhs
is masked to produce a value in the range 0..<lhs.bitWidth
. The
shift is performed using this masked value.
The following example defines x
as an instance of UInt8
, an 8-bit,
unsigned integer type. If you use 2
as the right-hand-side value in an
operation on x
, the shift amount requires no masking.
var x: UInt8 = 30 // 0b00011110
x &>>= 2
// x == 7 // 0b00000111
However, if you use 19
as rhs
, the operation first bitmasks rhs
to
3
, and then uses that masked value as the number of bits to shift lhs
.
var y: UInt8 = 30 // 0b00011110
y &>>= 19
// y == 3 // 0b00000011
Parameters:
lhs: The value to shift.
rhs: The number of bits to shift lhs
to the right. If rhs
is
outside the range 0..<lhs.bitWidth
, it is masked to produce a
value within that range.
Declaration
func &>>=<Other>(lhs: inout Self, rhs: Other)
Returns the difference of the two given values, discarding any overflow.
The masking subtraction operator (&-
) silently discards any overflow
that occurs during the operation. In the following example, the
difference of 10
and 21
is less than zero, the minimum representable
UInt
value, so the result is the overflowed value:
let x: UInt8 = 21 &- 10
// x == 11
let y: UInt8 = 10 &- 21
// y == 245 (after overflow)
Parameters:
lhs: A numeric value.
rhs: The value to subtract from lhs
.
Declaration
func &-(lhs: Self, rhs: Self) -> Self
Subtracts the second value from the first and stores the difference in the left-hand-side variable, discarding any overflow.
The masking subtraction assignment operator (&-=
) silently discards any
overflow that occurs during the operation. In the following example, the
difference of 10
and 21
is less than zero, the minimum representable
UInt
value, so the result is the overflowed value:
var x: Int8 = 21
x &-= 10
// x == 11
var y: UInt8 = 10
y &-= 21
// y == 245 (after overflow)
Parameters:
lhs: A numeric value.
rhs: The value to subtract from lhs
.
Declaration
func &-=(lhs: inout Self, rhs: Self)
Returns the given number unchanged.
You can use the unary plus operator (+
) to provide symmetry in your
code for positive numbers when also using the unary minus operator.
let x = -21
let y = +21
// x == -21
// y == 21
Returns: The given argument without any changes.
Declaration
prefix func +(x: Self) -> Self
Declared In
BinaryInteger
Adds two values and produces their sum.
The addition operator (+
) calculates the sum of its two arguments. For
example:
1 + 2 // 3
-10 + 15 // 5
-15 + -5 // -20
21.5 + 3.25 // 24.75
You cannot use +
with arguments of different types. To add values of
different types, convert one of the values to the other value's type.
let x: Int8 = 21
let y: Int = 1000000
Int(x) + y // 1000021
Parameters: lhs: The first value to add. rhs: The second value to add.
Declaration
func +(lhs: Self, rhs: Self.Stride) -> Self
Declared In
BinaryInteger
Adds two values and produces their sum.
The addition operator (+
) calculates the sum of its two arguments. For
example:
1 + 2 // 3
-10 + 15 // 5
-15 + -5 // -20
21.5 + 3.25 // 24.75
You cannot use +
with arguments of different types. To add values of
different types, convert one of the values to the other value's type.
let x: Int8 = 21
let y: Int = 1000000
Int(x) + y // 1000021
Parameters: lhs: The first value to add. rhs: The second value to add.
Declaration
func +(lhs: Self.Stride, rhs: Self) -> Self
Declared In
BinaryInteger
Adds two values and stores the result in the left-hand-side variable.
Parameters: lhs: The first value to add. rhs: The second value to add.
Declaration
func +=(lhs: inout Self, rhs: Self.Stride)
Declared In
BinaryInteger
Returns a partial range up to, and including, its upper bound.
Use the prefix closed range operator (prefix ...
) to create a partial
range of any type that conforms to the Comparable
protocol. This
example creates a PartialRangeThrough<Double>
instance that includes
any value less than or equal to 5.0
.
let throughFive = ...5.0
throughFive.contains(4.0) // true
throughFive.contains(5.0) // true
throughFive.contains(6.0) // false
You can use this type of partial range of a collection's indices to represent the range from the start of the collection up to, and including, the partial range's upper bound.
let numbers = [10, 20, 30, 40, 50, 60, 70]
print(numbers[...3])
// Prints "[10, 20, 30, 40]"
maximum
: The upper bound for the range.
Declaration
prefix func ...(maximum: Self) -> PartialRangeThrough<Self>
Declared In
BinaryInteger
Returns a closed range that contains both of its bounds.
Use the closed range operator (...
) to create a closed range of any type
that conforms to the Comparable
protocol. This example creates a
ClosedRange<Character>
from "a" up to, and including, "z".
let lowercase = "a"..."z"
print(lowercase.contains("z"))
// Prints "true"
Parameters: minimum: The lower bound for the range. maximum: The upper bound for the range.
Declaration
func ...(minimum: Self, maximum: Self) -> ClosedRange<Self>
Declared In
BinaryInteger
Returns a partial range up to, but not including, its upper bound.
Use the prefix half-open range operator (prefix ..<
) to create a
partial range of any type that conforms to the Comparable
protocol.
This example creates a PartialRangeUpTo<Double>
instance that includes
any value less than 5.0
.
let upToFive = ..<5.0
upToFive.contains(3.14) // true
upToFive.contains(6.28) // false
upToFive.contains(5.0) // false
You can use this type of partial range of a collection's indices to represent the range from the start of the collection up to, but not including, the partial range's upper bound.
let numbers = [10, 20, 30, 40, 50, 60, 70]
print(numbers[..<3])
// Prints "[10, 20, 30]"
maximum
: The upper bound for the range.
Declaration
prefix func ..<(maximum: Self) -> PartialRangeUpTo<Self>
Declared In
BinaryInteger
Returns a half-open range that contains its lower bound but not its upper bound.
Use the half-open range operator (..<
) to create a range of any type
that conforms to the Comparable
protocol. This example creates a
Range<Double>
from zero up to, but not including, 5.0.
let lessThanFive = 0.0..<5.0
print(lessThanFive.contains(3.14)) // Prints "true"
print(lessThanFive.contains(5.0)) // Prints "false"
Parameters: minimum: The lower bound for the range. maximum: The upper bound for the range.
Declaration
func ..<(minimum: Self, maximum: Self) -> Range<Self>
Declared In
BinaryInteger
Returns a Boolean value indicating whether the value of the first argument is less than that of the second argument.
You can compare instances of any BinaryInteger
types using the
less-than operator (<
), even if the two instances are of different
types.
Parameters: lhs: An integer to compare. rhs: Another integer to compare.
Declaration
func <<Other>(lhs: Self, rhs: Other) -> Bool where Other : BinaryInteger
Declared In
BinaryInteger
Returns the result of shifting a value's binary representation the specified number of digits to the left.
The <<
operator performs a smart shift, which defines a result for a
shift of any value.
- Using a negative value for
rhs
performs a right shift usingabs(rhs)
. - Using a value for
rhs
that is greater than or equal to the bit width oflhs
is an overshift, resulting in zero. - Using any other value for
rhs
performs a left shift onlhs
by that amount.
The following example defines x
as an instance of UInt8
, an 8-bit,
unsigned integer type. If you use 2
as the right-hand-side value in an
operation on x
, the value is shifted left by two bits.
let x: UInt8 = 30 // 0b00011110
let y = x << 2
// y == 120 // 0b01111000
If you use 11
as rhs
, x
is overshifted such that all of its bits
are set to zero.
let z = x << 11
// z == 0 // 0b00000000
Using a negative value as rhs
is the same as performing a right shift
with abs(rhs)
.
let a = x << -3
// a == 3 // 0b00000011
let b = x >> 3
// b == 3 // 0b00000011
Parameters:
lhs: The value to shift.
rhs: The number of bits to shift lhs
to the left.
Declaration
func <<<Other>(lhs: Self, rhs: Other) -> Self where Other : BinaryInteger
Declared In
FixedWidthInteger
, BinaryInteger
Returns a Boolean value indicating whether the value of the first argument is less than or equal to that of the second argument.
Parameters: lhs: A value to compare. rhs: Another value to compare.
Declaration
func <=(lhs: Self, rhs: Self) -> Bool
Declared In
BinaryInteger
Returns a Boolean value indicating whether the value of the first argument is less than or equal to that of the second argument.
This is the default implementation of the less-than-or-equal-to
operator (<=
) for any type that conforms to Comparable
.
Parameters: lhs: A value to compare. rhs: Another value to compare.
Declaration
func <=(lhs: Self, rhs: Self) -> Bool
Declared In
BinaryInteger
Returns a Boolean value indicating whether the value of the first argument is less than or equal to that of the second argument.
You can compare instances of any BinaryInteger
types using the
less-than-or-equal-to operator (<=
), even if the two instances are of
different types.
Parameters: lhs: An integer to compare. rhs: Another integer to compare.
Declaration
func <=<Other>(lhs: Self, rhs: Other) -> Bool where Other : BinaryInteger
Declared In
BinaryInteger
Returns a Boolean value indicating whether the two given values are equal.
You can check the equality of instances of any BinaryInteger
types
using the equal-to operator (==
). For example, you can test whether
the first UInt8
value in a string's UTF-8 encoding is equal to the
first UInt32
value in its Unicode scalar view:
let gameName = "Red Light, Green Light"
if let firstUTF8 = gameName.utf8.first,
let firstScalar = gameName.unicodeScalars.first?.value {
print("First code values are equal: \(firstUTF8 == firstScalar)")
}
// Prints "First code values are equal: true"
Parameters: lhs: An integer to compare. rhs: Another integer to compare.
Declaration
func ==<Other>(lhs: Self, rhs: Other) -> Bool where Other : BinaryInteger
Declared In
BinaryInteger
Returns a Boolean value indicating whether the value of the first argument is greater than that of the second argument.
Parameters: lhs: A value to compare. rhs: Another value to compare.
Declaration
func >(lhs: Self, rhs: Self) -> Bool
Declared In
BinaryInteger
Returns a Boolean value indicating whether the value of the first argument is greater than that of the second argument.
This is the default implementation of the greater-than operator (>
) for
any type that conforms to Comparable
.
Parameters: lhs: A value to compare. rhs: Another value to compare.
Declaration
func >(lhs: Self, rhs: Self) -> Bool
Declared In
BinaryInteger
Returns a Boolean value indicating whether the value of the first argument is greater than that of the second argument.
You can compare instances of any BinaryInteger
types using the
greater-than operator (>
), even if the two instances are of different
types.
Parameters: lhs: An integer to compare. rhs: Another integer to compare.
Declaration
func ><Other>(lhs: Self, rhs: Other) -> Bool where Other : BinaryInteger
Declared In
BinaryInteger
Returns a Boolean value indicating whether the value of the first argument is greater than or equal to that of the second argument.
Parameters: lhs: A value to compare. rhs: Another value to compare.
Declaration
func >=(lhs: Self, rhs: Self) -> Bool
Declared In
BinaryInteger
Returns a Boolean value indicating whether the value of the first argument is greater than or equal to that of the second argument.
This is the default implementation of the greater-than-or-equal-to operator
(>=
) for any type that conforms to Comparable
.
Parameters:
lhs: A value to compare.
rhs: Another value to compare.
Returns: true
if lhs
is greater than or equal to rhs
; otherwise,
false
.
Declaration
func >=(lhs: Self, rhs: Self) -> Bool
Declared In
BinaryInteger
Returns a Boolean value indicating whether the value of the first argument is greater than or equal to that of the second argument.
You can compare instances of any BinaryInteger
types using the
greater-than-or-equal-to operator (>=
), even if the two instances are
of different types.
Parameters: lhs: An integer to compare. rhs: Another integer to compare.
Declaration
func >=<Other>(lhs: Self, rhs: Other) -> Bool where Other : BinaryInteger
Declared In
BinaryInteger
Returns the result of shifting a value's binary representation the specified number of digits to the right.
The >>
operator performs a smart shift, which defines a result for a
shift of any value.
- Using a negative value for
rhs
performs a left shift usingabs(rhs)
. - Using a value for
rhs
that is greater than or equal to the bit width oflhs
is an overshift. An overshift results in-1
for a negative value oflhs
or0
for a nonnegative value. - Using any other value for
rhs
performs a right shift onlhs
by that amount.
The following example defines x
as an instance of UInt8
, an 8-bit,
unsigned integer type. If you use 2
as the right-hand-side value in an
operation on x
, the value is shifted right by two bits.
let x: UInt8 = 30 // 0b00011110
let y = x >> 2
// y == 7 // 0b00000111
If you use 11
as rhs
, x
is overshifted such that all of its bits
are set to zero.
let z = x >> 11
// z == 0 // 0b00000000
Using a negative value as rhs
is the same as performing a left shift
using abs(rhs)
.
let a = x >> -3
// a == 240 // 0b11110000
let b = x << 3
// b == 240 // 0b11110000
Right shift operations on negative values "fill in" the high bits with ones instead of zeros.
let q: Int8 = -30 // 0b11100010
let r = q >> 2
// r == -8 // 0b11111000
let s = q >> 11
// s == -1 // 0b11111111
Parameters:
lhs: The value to shift.
rhs: The number of bits to shift lhs
to the right.
Declaration
func >><Other>(lhs: Self, rhs: Other) -> Self where Other : BinaryInteger
Declared In
FixedWidthInteger
, BinaryInteger
Returns the result of performing a bitwise XOR operation on the two given values.
A bitwise XOR operation, also known as an exclusive OR operation, results
in a value that has each bit set to 1
where one or the other but not
both of its arguments had that bit set to 1
. For example:
let x: UInt8 = 5 // 0b00000101
let y: UInt8 = 14 // 0b00001110
let z = x ^ y // 0b00001011
// z == 11
Parameters: lhs: An integer value. rhs: Another integer value.
Declaration
func ^(lhs: Self, rhs: Self) -> Self
Declared In
BinaryInteger
Returns the result of performing a bitwise OR operation on the two given values.
A bitwise OR operation results in a value that has each bit set to 1
where one or both of its arguments have that bit set to 1
. For
example:
let x: UInt8 = 5 // 0b00000101
let y: UInt8 = 14 // 0b00001110
let z = x | y // 0b00001111
// z == 15
Parameters: lhs: An integer value. rhs: Another integer value.
Declaration
func |(lhs: Self, rhs: Self) -> Self
Declared In
BinaryInteger
Returns the inverse of the bits set in the argument.
The bitwise NOT operator (~
) is a prefix operator that returns a value
in which all the bits of its argument are flipped: Bits that are 1
in
the argument are 0
in the result, and bits that are 0
in the argument
are 1
in the result. This is equivalent to the inverse of a set. For
example:
let x: UInt8 = 5 // 0b00000101
let notX = ~x // 0b11111010
Performing a bitwise NOT operation on 0 returns a value with every bit
set to 1
.
let allOnes = ~UInt8.min // 0b11111111
Complexity: O(1).
Declaration
prefix func ~(x: Self) -> Self
Subtracts one value from another and produces their difference.
The subtraction operator (-
) calculates the difference of its two
arguments. For example:
8 - 3 // 5
-10 - 5 // -15
100 - -5 // 105
10.5 - 100.0 // -89.5
You cannot use -
with arguments of different types. To subtract values
of different types, convert one of the values to the other value's type.
let x: UInt8 = 21
let y: UInt = 1000000
y - UInt(x) // 999979
Parameters:
lhs: A numeric value.
rhs: The value to subtract from lhs
.
Declaration
func -(lhs: Self, rhs: Self) -> Self.Stride
Declared In
BinaryInteger
Subtracts one value from another and produces their difference.
The subtraction operator (-
) calculates the difference of its two
arguments. For example:
8 - 3 // 5
-10 - 5 // -15
100 - -5 // 105
10.5 - 100.0 // -89.5
You cannot use -
with arguments of different types. To subtract values
of different types, convert one of the values to the other value's type.
let x: UInt8 = 21
let y: UInt = 1000000
y - UInt(x) // 999979
Parameters:
lhs: A numeric value.
rhs: The value to subtract from lhs
.
Declaration
func -(lhs: Self, rhs: Self.Stride) -> Self
Declared In
BinaryInteger
Subtracts the second value from the first and stores the difference in the left-hand-side variable.
Parameters:
lhs: A numeric value.
rhs: The value to subtract from lhs
.
Declaration
func -=(lhs: inout Self, rhs: Self.Stride)
Declared In
BinaryInteger
Returns a value that is offset the specified distance from this value.
Use the advanced(by:)
method in generic code to offset a value by a
specified distance. If you're working directly with numeric values, use
the addition operator (+
) instead of this method.
For a value x
, a distance n
, and a value y = x.advanced(by: n)
,
x.distance(to: y) == n
.
n
: The distance to advance this value.
Returns: A value that is offset from this value by n
.
Declaration
func advanced(by n: Int) -> Self
Declared In
BinaryInteger
Returns the distance from this value to the given value, expressed as a stride.
For two values x
and y
, and a distance n = x.distance(to: y)
,
x.advanced(by: n) == y
.
other
: The value to calculate the distance to.
Returns: The distance from this value to other
.
Declaration
func distance(to other: Self) -> Int
Declared In
BinaryInteger
Returns the quotient and remainder of this value divided by the given value.
Use this method to calculate the quotient and remainder of a division at the same time.
let x = 1_000_000
let (q, r) = x.quotientAndRemainder(dividingBy: 933)
// q == 1071
// r == 757
rhs
: The value to divide this value by.
Returns: A tuple containing the quotient and remainder of this value
divided by rhs
.
Declaration
func quotientAndRemainder(dividingBy rhs: Self) -> (quotient: Self, remainder: Self)
Declared In
BinaryInteger
Returns -1
if this value is negative and 1
if it's positive;
otherwise, 0
.
Returns: The sign of this number, expressed as an integer of the same type.
Declaration
func signum() -> Self
Declared In
BinaryInteger
Returns the sum of this value and the given value without checking for arithmetic overflow.
Use this function only to avoid the cost of overflow checking when you
are certain that the operation won't overflow. In optimized builds (-O
)
the compiler is free to assume that overflow won't occur. Failure to
satisfy that assumption is a serious programming error and could lead to
statements being unexpectedly executed or skipped.
In debug builds (-Onone
) a runtime error is still triggered if the
operation overflows.
rhs
: The value to add to this value.
Returns: The sum of this value and rhs
.
Declaration
func unsafeAdding(_ other: Self) -> Self
Returns the quotient obtained by dividing this value by the given value without checking for arithmetic overflow.
Use this function only to avoid the cost of overflow checking when you
are certain that the operation won't overflow. In optimized builds (-O
)
the compiler is free to assume that overflow won't occur. Failure to
satisfy that assumption is a serious programming error and could lead to
statements being unexpectedly executed or skipped.
In debug builds (-Onone
) a runtime error is still triggered if the
operation overflows.
rhs
: The value to divide this value by.
Returns: The result of dividing this value by rhs
.
Declaration
func unsafeDivided(by other: Self) -> Self
Returns the product of this value and the given value without checking for arithmetic overflow.
Use this function only to avoid the cost of overflow checking when you
are certain that the operation won't overflow. In optimized builds (-O
)
the compiler is free to assume that overflow won't occur. Failure to
satisfy that assumption is a serious programming error and could lead to
statements being unexpectedly executed or skipped.
In debug builds (-Onone
) a runtime error is still triggered if the
operation overflows.
rhs
: The value to multiply by this value.
Returns: The product of this value and rhs
.
Declaration
func unsafeMultiplied(by other: Self) -> Self
Returns the difference obtained by subtracting the given value from this value without checking for arithmetic overflow.
Use this function only to avoid the cost of overflow checking when you
are certain that the operation won't overflow. In optimized builds (-O
)
the compiler is free to assume that overflow won't occur. Failure to
satisfy that assumption is a serious programming error and could lead to
statements being unexpectedly executed or skipped.
In debug builds (-Onone
) a runtime error is still triggered if the
operation overflows.
rhs
: The value to subtract from this value.
Returns: The result of subtracting rhs
from this value.
Declaration
func unsafeSubtracting(_ other: Self) -> Self
Where Magnitude : UnsignedInteger, Stride : SignedInteger
Returns a random value within the specified range.
Use this method to generate an integer within a specific range. This
example creates three new values in the range 1...100
.
for _ in 1...3 {
print(Int.random(in: 1...100))
}
// Prints "53"
// Prints "64"
// Prints "5"
This method uses the default random generator, Random.default
. The call
to Int.random(in: 1...100)
above is equivalent to calling
Int.random(in: 1...100, using: &Random.default)
.
range
: The range in which to create a random value.
Returns: A random value within the bounds of range
.
Declaration
static func random(in range: ClosedRange<Self>) -> Self
Returns a random value within the specified range.
Use this method to generate an integer within a specific range. This
example creates three new values in the range 1..<100
.
for _ in 1...3 {
print(Int.random(in: 1..<100))
}
// Prints "53"
// Prints "64"
// Prints "5"
This method uses the default random generator, Random.default
. The call
to Int.random(in: 1..<100)
above is equivalent to calling
Int.random(in: 1..<100, using: &Random.default)
.
range
: The range in which to create a random value.
range
must not be empty.
Returns: A random value within the bounds of range
.
Declaration
static func random(in range: Range<Self>) -> Self
Returns a random value within the specified range, using the given generator as a source for randomness.
Use this method to generate an integer within a specific range when you
are using a custom random number generator. This example creates three
new values in the range 1...100
.
for _ in 1...3 {
print(Int.random(in: 1...100, using: &myGenerator))
}
// Prints "7"
// Prints "44"
// Prints "21"
Parameters:
range: The range in which to create a random value.
generator: The random number generator to use when creating the
new random value.
Returns: A random value within the bounds of range
.
Declaration
static func random<T>(in range: ClosedRange<Self>, using generator: inout T) -> Self where T : RandomNumberGenerator
Returns a random value within the specified range, using the given generator as a source for randomness.
Use this method to generate an integer within a specific range when you
are using a custom random number generator. This example creates three
new values in the range 1..<100
.
for _ in 1...3 {
print(Int.random(in: 1..<100, using: &myGenerator))
}
// Prints "7"
// Prints "44"
// Prints "21"
Parameters:
range: The range in which to create a random value.
range
must not be empty.
generator: The random number generator to use when creating the
new random value.
Returns: A random value within the bounds of range
.
Declaration
static func random<T>(in range: Range<Self>, using generator: inout T) -> Self where T : RandomNumberGenerator
Where Stride : SignedInteger
Returns a countable closed range that contains both of its bounds.
Use the closed range operator (...
) to create a closed range of any type
that conforms to the Strideable
protocol with an associated signed
integer Stride
type, such as any of the standard library's integer
types. This example creates a ClosedRange<Int>
from zero up to,
and including, nine.
let singleDigits = 0...9
print(singleDigits.contains(9))
// Prints "true"
You can use sequence or collection methods on the singleDigits
range.
print(singleDigits.count)
// Prints "10"
print(singleDigits.last)
// Prints "9"
Parameters:)`. minimum: The lower bound for the range. maximum: The upper bound for the range.
Declaration
func ...(minimum: Self, maximum: Self) -> ClosedRange<Self>
Declared In
BinaryInteger
An integer type that uses a fixed size for every instance.
The
FixedWidthInteger
protocol adds binary bitwise operations, bit shifts, and overflow handling to the operations supported by theBinaryInteger
protocol.Use the
FixedWidthInteger
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 abinaryString
property on every fixed-width integer that represents the number's binary representation, split into 8-bit chunks.The
binaryString
implementation uses the staticbitWidth
property and the right shift operator (<<
), both of which are available to any type that conforms to theFixedWidthInteger
protocol.The next example declares a generic
squared
function, which accepts an instancex
of any fixed-width integer type. The function uses themultipliedReportingOverflow(by:)
method to multiplyx
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
FixedWidthInteger
protocol, declare the required initializers, properties, and methods. The required methods that are suffixed withReportingOverflow
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.