Generic Initializer

init(truncatingIfNeeded:)

Creates a new instance from the bit pattern of the given instance by truncating or sign-extending if needed to fit this type. もしこの型に適合するのに必要ならば切り詰めるか符号拡張によって、指定インスタンスのビットパターンから新しいインスタンスを作成します。

Declaration 宣言

init<T>(truncatingIfNeeded source: T) where T : BinaryInteger

Parameters パラメータ

source

An integer to convert to this type. この型へと変換する整数。

Discussion 解説

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. Tsourceの型)のビット幅がこの型のもつビット幅と等しいかより大きいならば、結果はsourceの先端を切った最下位ビットです。例えば、16bit値を8bit型へ変換する場合、sourceの最も下位の8ビットが使われます。


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. Tのビット幅がこの型のもつビット幅より小さいならば、結果は残りのビットを満たすように符号拡張されます。すなわち、sourceが負ならば、結果は1で詰め物をされます;そうでなければ、結果はゼロで詰め物をされます。


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