当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Swift UInt init(truncatingIfNeeded:)用法及代码示例


初始化器

init(truncatingIfNeeded:)

通过截断或sign-extending(如果需要适合此类型)从给定实例的位模式创建一个新实例。

声明

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

参数

source

要转换为此类型的整数。

详述

T(source的类型)的位宽等于或大于该类型的位宽时,结果是截断了source的最低有效位。例如,将 16 位值转换为 8 位类型时,仅使用 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

T的位宽小于该类型的位宽时,结果为sign-extended来填充剩余的位。也就是说,如果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

可用版本

iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+

相关用法


注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 UInt init(truncatingIfNeeded:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。