protocol BinaryInteger
Inheritance 
Comparable, CustomStringConvertible, Equatable, ExpressibleByIntegerLiteral, Hashable, Numeric, Strideable
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 floatingpoint types are all valid types
for Magnitude : Comparable, Numeric
A type that can represent the absolute value of any possible value of the conforming type. Stride : Comparable, SignedNumeric
A type that represents the distance between two values. 
Import  import Swift 
Initializers
Creates an integer from the given floatingpoint 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 floatingpoint value to convert to an integer.
source
must be representable in this type after rounding toward
zero.
Declaration
init<T>(_ source: T)
Creates a new instance from the given integer.
If the value passed as source
is not representable in this type, a
runtime error may occur.
let x = 500 as Int
let y = Int32(x)
// y == 500
// 500 is not representable as a 'UInt32' instance
let z = UInt32(x)
// Error
source
: An integer to convert. source
must be representable
in this type.
Declaration
init<T>(_ source: T)
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)
Creates a new instance from the bit pattern of the given instance by signextending 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
leastsignificant bits of source
. For example, when converting a
16bit value to an 8bit 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 signextended 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 an integer from the given floatingpoint 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 floatingpoint 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
Static Variables
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 }
Instance Variables
The number of bits in the current binary representation of this value.
This property is a constant for instances of fixedwidth integer types.
Declaration
var bitWidth: Int { get }
The number of trailing zeros in this value's binary representation.
For example, in a fixedwidth 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 }
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 }
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
Divides the first value by the second and stores the remainder in the lefthandside 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)
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
Stores the result of performing a bitwise AND operation on the two given values in the lefthandside 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)
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 lefthandside 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 lefthandside 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
Divides the first value by the second and stores the quotient in the lefthandside 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)
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 8bit,
unsigned integer type. If you use 2
as the righthandside 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
Stores the result of shifting a value's binary representation the specified number of digits to the left in the lefthandside 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 8bit,
unsigned integer type. If you use 2
as the righthandside 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)
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 in1
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 8bit,
unsigned integer type. If you use 2
as the righthandside 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
Stores the result of shifting a value's binary representation the specified number of digits to the right in the lefthandside 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 in1
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 8bit,
unsigned integer type. If you use 2
as the righthandside 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)
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
Stores the result of performing a bitwise XOR operation on the two given values in the lefthandside 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)
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
Stores the result of performing a bitwise OR operation on the two given values in the lefthandside 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)
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
Declared In
BinaryInteger
, Numeric
Subtracts the second value from the first and stores the difference in the lefthandside 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 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
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
compiletime 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 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)
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
Default Implementations
Creates a new value equal to zero.
Declaration
init()
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
ExpressibleByIntegerLiteral
A textual representation of this value.
Declaration
var description: String { get }
Declaration
func !=(lhs: Self, rhs: Self) > Bool
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 notequalto 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
Equatable
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 notequalto operator (!=
). For example, you can test
whether the first UInt8
value in a string's UTF8 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
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
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
Numeric
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
Comparable
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
Comparable
Returns a partial range up to, but not including, its upper bound.
Use the prefix halfopen 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
Comparable
Returns a halfopen range that contains its lower bound but not its upper bound.
Use the halfopen 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
Comparable
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
lessthan 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
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 8bit,
unsigned integer type. If you use 2
as the righthandside 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
Declaration
func <=(lhs: Self, rhs: Self) > Bool
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 lessthanorequalto
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
Comparable
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
lessthanorequalto 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
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 equalto operator (==
). For example, you can test whether
the first UInt8
value in a string's UTF8 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
Declaration
func >(lhs: Self, rhs: Self) > Bool
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 greaterthan 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
Comparable
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
greaterthan 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
Declaration
func >=(lhs: Self, rhs: Self) > Bool
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 greaterthanorequalto 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
Comparable
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
greaterthanorequalto 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
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 in1
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 8bit,
unsigned integer type. If you use 2
as the righthandside 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
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
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
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
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
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)
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
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
Strideable
An integer type with a binary representation.
The
BinaryInteger
protocol is the basis for all the integer types provided by the standard library. All of the standard library's integer types, such asInt
andUInt32
, conform toBinaryInteger
.Converting Between Numeric Types
You can create new instances of a type that conforms to the
BinaryInteger
protocol from a floatingpoint number or another binary integer of any type. TheBinaryInteger
protocol provides initializers for four different kinds of conversion.RangeChecked Conversion
You use the default
init(_:)
initializer to create a new instance when you're sure that the value passed is representable in the new type. For example, an instance ofInt16
can represent the value500
, so the first conversion in the code sample below succeeds. That same value is too large to represent as anInt8
instance, so the second conversion fails, triggering a runtime error.When you create a binary integer from a floatingpoint value using the default initializer, the value is rounded toward zero before the range is checked. In the following example, the value
127.75
is rounded to127
, which is representable by theInt8
type.128.25
is rounded to128
, which is not representable as anInt8
instance, triggering a runtime error.Exact Conversion
Use the
init?(exactly:)
initializer to create a new instance after checking whether the passed value is representable. Instead of trapping on outofrange values, using the failableexact
initializer results innil
.When converting floatingpoint values, the
init?(exact:)
initializer checks both that the passed value has no fractional part and that the value is representable in the resulting type.Clamping Conversion
Use the
init(clamping:)
initializer to create a new instance of a binary integer type where outofrange values are clamped to the representable range of the type. For a typeT
, the resulting value is in the rangeT.min...T.max
.Bit Pattern Conversion
Use the
init(truncatingIfNeeded:)
initializer to create a new instance with the same bit pattern as the passed value, extending or truncating the value's representation as necessary. Note that the value may not be preserved, particularly when converting between signed to unsigned integer types or when the destination type has a smaller bit width than the source type. The following example shows how extending and truncating work for nonnegative integers:Any padding is performed by signextending the passed value. When nonnegative integers are extended, the result is padded with zeroes. When negative integers are extended, the result is padded with ones. This example shows several extending conversions of a negative valuenote that negative values are signextended even when converting to an unsigned type.
Comparing Across Integer Types
You can use relational operators, such as the lessthan and equalto operators (
<
and==
), to compare instances of different binary integer types. The following example compares instances of theInt
,UInt
, andUInt8
types: