結構
Bool
其實例為
true
或 false
的值類型。聲明
@frozen struct Bool
概述
Bool
表示 Swift 中的布爾值。通過使用布爾文字 true
或 false
之一,或者通過將布爾方法或操作的結果分配給變量或常量來創建 Bool
的實例。
var godotHasArrived = false
let numbers = 1...5
let containsTen = numbers.contains(10)
print(containsTen)
// Prints "false"
let (a, b) = (100, 101)
let aFirst = a < b
print(aFirst)
// Prints "true"
Swift 在條件上下文中僅使用簡單的布爾值來幫助避免意外的編程錯誤並幫助保持每個控製語句的清晰性。與其他編程語言不同,在 Swift 中,整數和字符串不能用於需要布爾值的地方。
例如,以下代碼示例無法編譯,因為它嘗試在邏輯上下文中使用整數 i
:
var i = 5
while i {
print(i)
i -= 1
}
// error: Cannot convert value of type 'Int' to expected condition type 'Bool'
Swift 中的正確方法是將 i
值與 while
語句中的零進行比較。
while i != 0 {
print(i)
i -= 1
}
使用導入的布爾值
C bool
和 Boolean
類型以及 Objective-C BOOL
類型都作為 Bool
橋接到 Swift 中。 Swift 中的單一Bool
類型保證了從C 和Objective-C 導入的函數、方法和屬性具有一致的類型接口。
可用版本
iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+
相關用法
- Swift Bool !(_:)用法及代碼示例
- Swift Bool random()用法及代碼示例
- Swift Bool ||(_:_:)用法及代碼示例
- Swift Bool init(booleanLiteral:)用法及代碼示例
- Swift BooleanLiteralType用法及代碼示例
- Swift Bool random(using:)用法及代碼示例
- Swift Bool &&(_:_:)用法及代碼示例
- Swift Bool toggle()用法及代碼示例
- Swift BinaryInteger quotientAndRemainder(dividingBy:)用法及代碼示例
- Swift BinaryInteger trailingZeroBitCount用法及代碼示例
- Swift BinaryInteger init(clamping:)用法及代碼示例
- Swift BinaryInteger <<=(_:_:)用法及代碼示例
- Swift BinaryInteger !=(_:_:)用法及代碼示例
- Swift BinaryInteger /(_:_:)用法及代碼示例
- Swift BinaryInteger init(truncatingIfNeeded:)用法及代碼示例
- Swift BinaryInteger ==(_:_:)用法及代碼示例
- Swift BinaryFloatingPoint binade用法及代碼示例
- Swift BidirectionalCollection subscript(_:)用法及代碼示例
- Swift BidirectionalCollection last(where:)用法及代碼示例
- Swift BidirectionalCollection lastIndex(where:)用法及代碼示例
- Swift BinaryInteger init(_:)用法及代碼示例
- Swift BinaryInteger %=(_:_:)用法及代碼示例
- Swift BinaryFloatingPoint random(in:using:)用法及代碼示例
- Swift BinaryInteger &=(_:_:)用法及代碼示例
- Swift BidirectionalCollection lastIndex(of:)用法及代碼示例
注:本文由純淨天空篩選整理自apple.com大神的英文原創作品 Bool。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。