我在一些Swift代碼中寫入了Boolean
而不是Bool
,並且Xcode讓我用DarwinBoolean
替換它。什麼是Swift中的DarwinBoolean類型
問題是,究竟是什麼DarwinBoolean
?
與Bool
和ObjCBool
類型相比有什麼區別。 這是什麼目的?
我在一些Swift代碼中寫入了Boolean
而不是Bool
,並且Xcode讓我用DarwinBoolean
替換它。什麼是Swift中的DarwinBoolean類型
問題是,究竟是什麼DarwinBoolean
?
與Bool
和ObjCBool
類型相比有什麼區別。 這是什麼目的?
簡短的回答:
Bool
是本地雨燕爲真值。DarwinBoolean
是「歷史性」C型Boolean
的Swift映射。ObjCBool
是Objective-C類型BOOL
的Swift映射。你會在你的銀行代碼,除非其他類型 的一個需要與現有的核心基金會或 Objective-C的功能互操作使用Bool
。
進一步瞭解DarwinBoolean
: DarwinBoolean
在夫特定義爲
/// The `Boolean` type declared in MacTypes.h and used throughout Core
/// Foundation.
///
/// The C type is a typedef for `unsigned char`.
public struct DarwinBoolean : BooleanType, BooleanLiteralConvertible {
public init(_ value: Bool)
/// The value of `self`, expressed as a `Bool`.
public var boolValue: Bool { get }
/// Create an instance initialized to `value`.
public init(booleanLiteral value: Bool)
}
和是 「歷史」 C型Boolean
從 MacTypes.h迅映射:
/********************************************************************************
Boolean types and values
Boolean Mac OS historic type, sizeof(Boolean)==1
bool Defined in stdbool.h, ISO C/C++ standard type
false Now defined in stdbool.h
true Now defined in stdbool.h
*********************************************************************************/
typedef unsigned char Boolean;
另請參閱Xcode 7 R新聞稿注:
在MacTypes.h類型布爾在上下文的 允許夫特和Objective-C類型之間橋接導入爲布爾。
在其中表示是顯著情況下,布爾導入 作爲一個獨特的DarwinBoolean類型,這是BooleanLiteralConvertible ,可以在條件下使用(很像ObjCBool類型)。 (19013551)
作爲示例,所述功能
void myFunc1(Boolean b);
void myFunc2(Boolean *b);
被導入到快速作爲
public func myFunc1(b: Bool)
public func myFunc2(b: UnsafeMutablePointer<DarwinBoolean>)
在myFunc1
有天然 夫特型Bool
和之間的自動轉換Mac Type Boolean
。 這是不可能在myFunc2
,因爲地址的變量 被傳遞,這裏DarwinBoolean
正好是Mac型Boolean
。
在之前的Swift版本中 - 如果我沒有記錯的話 - 這個映射的 類型被稱爲Boolean
,之後又被重命名爲DarwinBoolean
。
進一步瞭解ObjCBool
: ObjCBool
是Objective-C的類型BOOL
的夫特映射, 這可以是signed char
或C/C++ bool
類型,這取決於 架構。例如,NSFileManager
方法
- (BOOL)fileExistsAtPath:(NSString *)path
isDirectory:(BOOL *)isDirectory
導入到快速作爲
func fileExistsAtPath(_ path: String,
isDirectory isDirectory: UnsafeMutablePointer<ObjCBool>) -> Bool
這裏BOOL
返回值被轉換爲Bool
自動, 但(BOOL *)
保持爲UnsafeMutablePointer<ObjCBool>
,因爲它是地址的一個變量。
不幸的是,除了在前面的答案中發佈的部分外,沒有真正的DarwinBoolean文檔。
但是,通常可以單獨導入或通過Foundation軟件包訪問的Darwin軟件包用於想要使用數學函數的情況。
DarwinBoolean
的值與正常的布爾值相同,爲true或false。