BinaryInteger

protocol BinaryInteger

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 as Int and UInt32, conform to BinaryInteger.

Converting Between Numeric Types

You can create new instances of a type that conforms to the BinaryInteger protocol from a floating-point number or another binary integer of any type. The BinaryInteger protocol provides initializers for four different kinds of conversion.

Range-Checked 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 of Int16 can represent the value 500, so the first conversion in the code sample below succeeds. That same value is too large to represent as an Int8 instance, so the second conversion fails, triggering a runtime error.

let x: Int = 500
let y = Int16(x)
// y == 500

let z = Int8(x)
// Error: Not enough bits to represent...

When you create a binary integer from a floating-point 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 to 127, which is representable by the Int8 type. 128.25 is rounded to 128, which is not representable as an Int8 instance, triggering a runtime error.

let e = Int8(127.75)
// e == 127

let f = Int8(128.25)
// Error: Double value cannot be converted...

Exact Conversion

Use the init?(exactly:) initializer to create a new instance after checking whether the passed value is representable. Instead of trapping on out-of-range values, using the failable exact initializer results in nil.

let x = Int16(exactly: 500)
// x == Optional(500)

let y = Int8(exactly: 500)
// y == nil

When converting floating-point 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.

let e = Int8(exactly: 23.0)       // integral value, representable
// e == Optional(23)

let f = Int8(exactly: 23.75)      // fractional value, representable
// f == nil

let g = Int8(exactly: 500.0)      // integral value, nonrepresentable
// g == nil

Clamping Conversion

Use the init(clamping:) initializer to create a new instance of a binary integer type where out-of-range values are clamped to the representable range of the type. For a type T, the resulting value is in the range T.min...T.max.

let x = Int16(clamping: 500)
// x == 500

let y = Int8(clamping: 500)
// y == 127

let z = UInt8(clamping: -500)
// z == 0

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:

let q: Int16 = 850
// q == 0b00000011_01010010

let r = Int8(truncatingIfNeeded: q)      // truncate 'q' to fit in 8 bits
// r == 82
//   == 0b01010010

let s = Int16(truncatingIfNeeded: r)     // extend 'r' to fill 16 bits
// s == 82
//   == 0b00000000_01010010

Any padding is performed by sign-extending 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 value---note that negative values are sign-extended even when converting to an unsigned type.

let t: Int8 = -100
// t == -100
// t's binary representation == 0b10011100

let u = UInt8(truncatingIfNeeded: t)
// u == 156
// u's binary representation == 0b10011100

let v = Int16(truncatingIfNeeded: t)
// v == -100
// v's binary representation == 0b11111111_10011100

let w = UInt16(truncatingIfNeeded: t)
// w == 65436
// w's binary representation == 0b11111111_10011100

Comparing Across Integer Types

You can use relational operators, such as the less-than and equal-to operators (< and ==), to compare instances of different binary integer types. The following example compares instances of the Int, UInt, and UInt8 types:

let x: Int = -23
let y: UInt = 1_000
let z: UInt8 = 23

if x < y {
    print("\(x) is less than \(y).")
}
// Prints "-23 is less than 1000."

if z > x {
    print("\(z) is greater than \(x).")
}
// Prints "23 is greater than -23."
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 Words type must conform to the Collection protocol with an Element type of UInt.

IntegerLiteralType : _ExpressibleByBuiltinIntegerLiteral

A type that represents an integer literal.

The standard library integer and floating-point types are all valid types for IntegerLiteralType.

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

init<T>(_: T) Required

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)
init<T>(_: T) Required

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)
init(clamping:) Required

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)
init(truncatingIfNeeded:) Required

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)
init?(exactly:) Required

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
init(integerLiteral:)

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

static var isSigned: Bool Required

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

var bitWidth: Int Required

The number of bits in the current binary representation of this value.

This property is a constant for instances of fixed-width integer types.

Declaration

var bitWidth: Int { get }
var trailingZeroBitCount: Int Required

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 }
var words: Self.Words Required

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 }
var description: String

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
var hashValue: Int Required

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
var magnitude: Self.Magnitude Required

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

func %(_:rhs:) Required

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
func %=(_:rhs:) Required

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)
func &(_:rhs:)

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
func &=(_:rhs:) Required

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)
func *(_:rhs:) Required

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
func *=(_:rhs:) Required

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
func +(_:rhs:)

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
func +=(_:rhs:)

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
func /(_:rhs:) Required

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
func /=(_:rhs:) Required

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)
func <(_:rhs:)

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
func <<(_:rhs:)

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 using abs(rhs).
  • Using a value for rhs that is greater than or equal to the bit width of lhs is an overshift, resulting in zero.
  • Using any other value for rhs performs a left shift on lhs 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
func <<=(_:rhs:) Required

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 using abs(rhs).
  • Using a value for rhs that is greater than or equal to the bit width of lhs is an overshift, resulting in zero.
  • Using any other value for rhs performs a left shift on lhs 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)
func <=(_: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
func ==(_:rhs:)

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
func >(_:rhs:)

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
func >=(_:rhs:)

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
func >>(_:rhs:)

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 using abs(rhs).
  • Using a value for rhs that is greater than or equal to the bit width of lhs is an overshift. An overshift results in -1 for a negative value of lhs or 0 for a nonnegative value.
  • Using any other value for rhs performs a right shift on lhs 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
func >>=(_:rhs:) Required

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 using abs(rhs).
  • Using a value for rhs that is greater than or equal to the bit width of lhs is an overshift. An overshift results in -1 for a negative value of lhs or 0 for a nonnegative value.
  • Using any other value for rhs performs a right shift on lhs 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)
func ^(_: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
func ^=(_:rhs:) Required

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)
func |(_:rhs:)

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
func |=(_:rhs:) Required

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)
prefix func ~(_:) Required

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
func -(_:rhs:)

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
func -=(_:rhs:)

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
func advanced(by:)

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
func distance(to:)

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
func hash(into:) Required

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
func quotientAndRemainder(dividingBy:)

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)
func signum()

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

init()

Creates a new value equal to zero.

Declaration

init()
init(integerLiteral:)

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
var description: String

A textual representation of this value.

Declaration

var description: String { get }
func !=(_: Self, rhs: Self)

Declaration

func !=(lhs: Self, rhs: Self) -> Bool
func !=(_:rhs:)

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

Equatable
func != <Other>(_: Self, rhs: Other)

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
func &(_:rhs:)

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
prefix func +(_:)

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
func +(_: Self, rhs: Self.Stride)

Declaration

func +(lhs: Self, rhs: Self.Stride) -> Self

Declared In

Strideable
func +(_: Self.Stride, rhs: Self)

Declaration

func +(lhs: Self.Stride, rhs: Self) -> Self

Declared In

Strideable
func +=(_:rhs:)

Declaration

func +=(lhs: inout Self, rhs: Self.Stride)

Declared In

Strideable
prefix func ...(_: Self)

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
func ...(_:maximum:)

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
prefix func ..<(_:)

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

Comparable
func ..<(_:maximum:)

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

Comparable
func <(_:rhs:)

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
func <(_:y:)

Declaration

func <(x: Self, y: Self) -> Bool

Declared In

Strideable
func <<(_:rhs:)

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 using abs(rhs).
  • Using a value for rhs that is greater than or equal to the bit width of lhs is an overshift, resulting in zero.
  • Using any other value for rhs performs a left shift on lhs 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
func <=(_: Self, rhs: Self)

Declaration

func <=(lhs: Self, rhs: Self) -> Bool
func <=(_:rhs:)

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

Comparable
func <= <Other>(_: Self, rhs: Other)

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
func ==(_:rhs:)

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
func ==(_:y:)

Declaration

func ==(x: Self, y: Self) -> Bool

Declared In

Strideable
func >(_: Self, rhs: Self)

Declaration

func >(lhs: Self, rhs: Self) -> Bool
func >(_:rhs:)

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

Comparable
func > <Other>(_: Self, rhs: Other)

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
func >=(_: Self, rhs: Self)

Declaration

func >=(lhs: Self, rhs: Self) -> Bool
func >=(_:rhs:)

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

Comparable
func >= <Other>(_: Self, rhs: Other)

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
func >>(_:rhs:)

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 using abs(rhs).
  • Using a value for rhs that is greater than or equal to the bit width of lhs is an overshift. An overshift results in -1 for a negative value of lhs or 0 for a nonnegative value.
  • Using any other value for rhs performs a right shift on lhs 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
func ^(_: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
func |(_:rhs:)

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
func -(_: Self, rhs: Self)

Declaration

func -(lhs: Self, rhs: Self) -> Self.Stride

Declared In

Strideable
func -(_: Self, rhs: Self.Stride)

Declaration

func -(lhs: Self, rhs: Self.Stride) -> Self

Declared In

Strideable
func -=(_:rhs:)

Declaration

func -=(lhs: inout Self, rhs: Self.Stride)

Declared In

Strideable
func advanced(by:)

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
func distance(to:)

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
func quotientAndRemainder(dividingBy:)

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)
func signum()

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

func ...(_:maximum:)

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