協議
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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。