InitializerSwiftFoundationSwift
init(_:)
Creates a new instance from the given integer.
Available because
Self
conforms toSignedInteger
.Available when
Self
conforms toFixedWidthInteger
init<T>(_ source: T) where T : BinaryInteger
Parameters
- source
A value to convert to this type of integer. The value passed as
source
must be representable in this type.
Overview
Use this initializer to convert from another integer type when you know the value is within the bounds of this type. Passing a value that can’t be represented in this type results in a runtime error.
In the following example, the constant y
is successfully created from x
, an Int
instance with a value of 100
. Because the Int8
type can represent 127
at maximum, the attempt to create z
with a value of 1000
results in a runtime error.
let x = 100
let y = Int8(x)
// y == 100
let z = Int8(x * 10)
// Error: Not enough bits to represent the given value