协议
Fixed
FixedWidthInteger
对每个实例使用固定大小的整数类型。
声明
protocol FixedWidthInteger : BinaryInteger, LosslessStringConvertible where Self.Magnitude : FixedWidthInteger, Self.Magnitude : UnsignedInteger, Self.Stride : FixedWidthInteger, Self.Stride : SignedInteger
概述
FixedWidthInteger
协议在BinaryInteger
协议支持的操作中添加了二进制位操作、位移和溢出处理。
在编写依赖于位移位、执行按位运算、捕获溢出或访问类型的最大或最小可表示值的操作时,使用 FixedWidthInteger
协议作为约束或扩展点。例如,以下代码为每个固定宽度整数提供了一个binaryString
属性,该属性表示数字的二进制表示,分为 8 位块。
extension FixedWidthInteger {
var binaryString: String {
var result: [String] = []
for i in 0..<(Self.bitWidth / 8) {
let byte = UInt8(truncatingIfNeeded: self >> (i * 8))
let byteString = String(byte, radix: 2)
let padding = String(repeating: "0",
count: 8 - byteString.count)
result.append(padding + byteString)
}
return "0b" + result.reversed().joined(separator: "_")
}
}
print(Int16.max.binaryString)
// Prints "0b01111111_11111111"
print((101 as UInt8).binaryString)
// Prints "0b11001001"
binaryString
实现使用静态 bitWidth
属性和右移运算符 (>>
),这两者都可用于符合 FixedWidthInteger
协议的任何类型。
下一个示例声明了一个通用 squared
函数,它接受任何固定宽度整数类型的实例 x
。该函数使用multipliedReportingOverflow(by:)
方法将x
与自身相乘,并检查结果是否太大而无法以相同类型表示。
func squared<T: FixedWidthInteger>(_ x: T) -> T? {
let (result, overflow) = x.multipliedReportingOverflow(by: x)
if overflow {
return nil
}
return result
}
let (x, y): (Int8, Int8) = (9, 123)
print(squared(x))
// Prints "Optional(81)"
print(squared(y))
// Prints "nil"
符合FixedWidthInteger 协议
要使您自己的自定义类型符合FixedWidthInteger
协议,请声明所需的初始化程序、属性和方法。以ReportingOverflow
为后缀的所需方法用作算术运算的自定义点。当您只提供这些方法时,标准库会为所有其他算术方法和运算符提供默认实现。
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
相关用法
- Swift FixedWidthInteger &-=(_:_:)用法及代码示例
- Swift FixedWidthInteger &<<=(_:_:)用法及代码示例
- Swift FixedWidthInteger &<<(_:_:)用法及代码示例
- Swift FixedWidthInteger multipliedFullWidth(by:)用法及代码示例
- Swift FixedWidthInteger &-(_:_:)用法及代码示例
- Swift FixedWidthInteger &*=(_:_:)用法及代码示例
- Swift FixedWidthInteger nonzeroBitCount用法及代码示例
- Swift FixedWidthInteger init(_:radix:)用法及代码示例
- Swift FixedWidthInteger random(in:)用法及代码示例
- Swift FixedWidthInteger &>>=(_:_:)用法及代码示例
- Swift FixedWidthInteger dividingFullWidth(_:)用法及代码示例
- Swift FixedWidthInteger leadingZeroBitCount用法及代码示例
- Swift FixedWidthInteger &>>(_:_:)用法及代码示例
- Swift FixedWidthInteger random(in:using:)用法及代码示例
- Swift FixedWidthInteger &+=(_:_:)用法及代码示例
- Swift FixedWidthInteger &*(_:_:)用法及代码示例
- Swift FixedWidthInteger &+(_:_:)用法及代码示例
- Swift FlattenSequence prefix(_:)用法及代码示例
- Swift Float -(_:)用法及代码示例
- Swift FlattenSequence max(by:)用法及代码示例
- Swift Float80 /(_:_:)用法及代码示例
- Swift Float ...(_:_:)用法及代码示例
- Swift FloatingPointRoundingRule.toNearestOrAwayFromZero用法及代码示例
- Swift Float16 ...(_:_:)用法及代码示例
- Swift FloatingPointRoundingRule.up用法及代码示例
注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 FixedWidthInteger。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。