struct UInt8
Inheritance 
BinaryInteger, CVarArg, Codable, Comparable, CustomPlaygroundQuickLookable, CustomReflectable, CustomStringConvertible, Equatable, ExpressibleByIntegerLiteral, FixedWidthInteger, Hashable, LosslessStringConvertible, Numeric, Strideable, UnsignedInteger, _BitwiseOperations
View Protocol Hierarchy →


Associated Types 
IntegerLiteralType = UInt8
A type that represents an integer literal. Magnitude = UInt8
A type that can represent the absolute value of any possible value of this type. 
Nested Types  UInt8.Words 
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(_ source: Double)
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(_ source: Float)
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(_ source: Float80)
Creates an integer from the given floatingpoint 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 floatingpoint value to convert to an integer.
source
must be representable in this type after rounding toward
zero.
Declaration
init<T>(_ source: T)
Declared In
FixedWidthInteger
, UnsignedInteger
Construct with value v.value
.
Precondition: v.value
can be represented as ASCII (0..<128).
Declaration
init(ascii v: Unicode.Scalar)
Creates an integer from its bigendian representation, changing the byte order if necessary.
value
: A value to use as the bigendian representation of the
new integer.
Declaration
init(bigEndian value: UInt8)
Declared In
FixedWidthInteger
Creates a new instance with the same memory representation as the given value.
This initializer does not perform any range or overflow checking. The
resulting instance may not have the same numeric value as
bitPattern
it is only guaranteed to use the same pattern of bits in
its binary representation.
x
: A value to use as the source of the new instance's binary
representation.
Declaration
init(bitPattern x: Int8)
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)
Declared In
FixedWidthInteger
Creates a new instance by decoding from the given decoder.
This initializer throws an error if reading from the decoder fails, or if the data read is corrupted or otherwise invalid.
decoder
: The decoder to read data from.
Declaration
init(from decoder: Decoder)
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: UInt8)
Declared In
FixedWidthInteger
Creates an integer from its littleendian representation, changing the byte order if necessary.
value
: A value to use as the littleendian representation of
the new integer.
Declaration
init(littleEndian value: UInt8)
Declared In
FixedWidthInteger
Creates a new instance from the bit pattern of the given instance by truncating or signextending 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
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)
Declared In
FixedWidthInteger
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 (09
) or letters
(az
or AZ
). 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("2150") // 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)
Declared In
FixedWidthInteger
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?(exactly source: Double)
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?(exactly source: Float)
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?(exactly source: Float80)
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
FixedWidthInteger
, UnsignedInteger
Static Variables
The number of bits used for the underlying binary representation of values of this type.
The bit width of an UInt8
instance is 8.
Declaration
static var bitWidth: Int { get }
A Boolean value indicating whether this type is a signed integer type.
This property is always false
for unsigned integer types.
Declaration
static var isSigned: Bool { get }
Declared In
UnsignedInteger
The maximum representable integer in this type.
For unsigned integer types, this value is (2 ** bitWidth)  1
, where
**
is exponentiation.
Declaration
static var max: UInt8 { get }
Declared In
UnsignedInteger
The minimum representable integer in this type.
For unsigned integer types, this value is always 0
.
Declaration
static var min: UInt8 { get }
Declared In
UnsignedInteger
Instance Variables
The bigendian 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 bigendian platform, for any
integer x
, x == x.bigEndian
.
Declaration
var bigEndian: UInt8 { get }
Declared In
FixedWidthInteger
A representation of this integer with the byte order swapped.
Declaration
var byteSwapped: UInt8 { get }
A mirror that reflects the UInt8
instance.
Declaration
var customMirror: Mirror { get }
A custom playground Quick Look for the UInt8
instance.
Deprecated: UInt8.customPlaygroundQuickLook will be removed in a future Swift version.
Declaration
var customPlaygroundQuickLook: PlaygroundQuickLook { get }
A textual representation of this value.
Declaration
var description: String { get }
Declared In
FixedWidthInteger
The integer's hash value.
The hash value is not guaranteed to be stable across different invocations of the same program. Do not persist the hash value across program runs.
Declaration
var hashValue: Int { get }
The number of leading zeros in this value's binary representation.
For example, in an 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 littleendian 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 littleendian platform, for any
integer x
, x == x.littleEndian
.
Declaration
var littleEndian: UInt8 { get }
Declared In
FixedWidthInteger
The magnitude of this value.
Every unsigned integer is its own magnitude, so for any value x
,
x == x.magnitude
.
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: UInt8 { get }
Declared In
UnsignedInteger
The number of bits equal to 1 in this value's binary representation.
For example, in a fixedwidth 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, 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.
Declaration
var words: UInt8.Words { get }
Instance Methods
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(_ other: UInt8) > (partialValue: UInt8, 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.
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) > UInt8
Declared In
FixedWidthInteger
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: UInt8) > Int
Declared In
FixedWidthInteger
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 other: UInt8) > (partialValue: UInt8, overflow: Bool)
Returns a tuple containing the quotient and remainder of dividing the given value by this value.
The resulting quotient must be representable within the bounds of the
type. If the quotient of dividing dividend
by this value is too large
to represent in the type, a runtime error may occur.
dividend
: A tuple containing the high and low parts of a
doublewidth integer. The high
component of the value carries the
sign, if the type is signed.
Returns: A tuple containing the quotient and remainder of dividend
divided by this value.
Declaration
func dividingFullWidth(_ dividend: (high: UInt8, low: UInt8.Magnitude)) > (quotient: UInt8, remainder: UInt8)
Encodes this value into the given encoder.
This function throws an error if any values are invalid for the given encoder's format.
encoder
: The encoder to write data to.
Declaration
func encode(to encoder: Encoder) throws
Hashes the essential components of this value by feeding them into the given hasher.
hasher
: The hasher to use when combining the components
of this instance.
Declaration
func hash(into hasher: inout Hasher)
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 UInt8
values that normally overflow when multiplied:
let x: UInt8 = 100
let y: UInt8 = 20
let result = x.multipliedFullWidth(by: y)
// result.high == 0b00000111
// result.low == 0b11010000
The product of x
and y
is 2000, which is too large to represent in a
UInt8
instance. The high
and low
properties of the result
value
represent 2000 when concatenated to form a doublewidth integer; that
is, using result.high
as the high byte and result.low
as the low byte
of a UInt16
instance.
let z = UInt16(result.high) << 8  UInt16(result.low)
// z == 2000
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: UInt8) > (high: UInt8, low: UInt8.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 other: UInt8) > (partialValue: UInt8, 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: UInt8) > (quotient: UInt8, remainder: UInt8)
Declared In
FixedWidthInteger
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 other: UInt8) > (partialValue: UInt8, 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() > UInt8
Declared In
UInt8
, FixedWidthInteger
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(_ other: UInt8) > (partialValue: UInt8, overflow: Bool)
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: UInt8) > UInt8
Declared In
FixedWidthInteger
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: UInt8) > UInt8
Declared In
FixedWidthInteger
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: UInt8) > UInt8
Declared In
FixedWidthInteger
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: UInt8) > UInt8
Declared In
FixedWidthInteger
Conditionally Inherited Items
The initializers, methods, and properties listed below may be available on this type under certain conditions (such as methods that are available on Array
when its elements are Equatable
) or may not ever be available if that determination is beyond SwiftDoc.org's capabilities. Please open an issue on GitHub if you see something out of place!
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<UInt8>) > UInt8
Declared In
FixedWidthInteger
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<UInt8>) > UInt8
Declared In
FixedWidthInteger
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<UInt8>, using generator: inout T) > UInt8 where T : RandomNumberGenerator
Declared In
FixedWidthInteger
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<UInt8>, using generator: inout T) > UInt8 where T : RandomNumberGenerator
Declared In
FixedWidthInteger
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: UInt8, maximum: UInt8) > ClosedRange<UInt8>
Declared In
FixedWidthInteger
An 8bit unsigned integer value type.