Generic Initializer

init(clamping:)

Creates a new instance with the representable value that’s closest to the given integer.

Declaration

init<Other>(clamping source: Other) where Other : BinaryInteger

Parameters

source

An integer to convert to this type.

Discussion

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

See Also

Converting Integers

init<T>(T)

Creates a new instance from the given integer.

init?<T>(exactly: T)

Creates a new instance from the given integer, if it can be represented exactly.

init<T>(truncatingIfNeeded: T)

Creates a new instance from the bit pattern of the given instance by truncating or sign-extending if needed to fit this type.

init(bitPattern: UInt)

Creates a new instance with the same memory representation as the given value.