什么是Swift中的DarwinBoolean类型

Dal*_*kar 16 swift

我已经编写Boolean而不是Bool在一些Swift代码中,Xcode让我替换它DarwinBoolean.

问题是,究竟是DarwinBoolean什么?

比较BoolObjCBool类型有什么不同.它的目的是什么?

Mar*_*n R 23

简短回答:

  • Bool 是真值的原生Swift类型.
  • DarwinBoolean是"历史性"C类型的Swift映射Boolean.
  • ObjCBool是Objective-C类型的Swift映射BOOL.

您将Bool在Swift代码中使用,除非与现有Core Foundation或Objective-C函数的互操作性需要其他类型之一.


更多关于DarwinBoolean: DarwinBoolean在Swift中被定义为

/// 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)
}
Run Code Online (Sandbox Code Playgroud)

和是"历史" C型的夫特映射BooleanMacTypes.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;
Run Code Online (Sandbox Code Playgroud)

另请参阅Xcode 7发行说明:

MacTypes.h中的类型Boolean在上下文中作为Bool导入,允许在Swift和Objective-C类型之间进行桥接.

在表示很重要的情况下,布尔值作为不同的DarwinBoolean类型导入,它是BooleanLiteralConvertible并且可以在条件中使用(很像ObjCBool​​类型).(19013551)

作为一个例子,功能

void myFunc1(Boolean b);
void myFunc2(Boolean *b);
Run Code Online (Sandbox Code Playgroud)

被导入Swift作为

public func myFunc1(b: Bool)
public func myFunc2(b: UnsafeMutablePointer<DarwinBoolean>)
Run Code Online (Sandbox Code Playgroud)

myFunc1原生Swift类型Bool和Mac Type 之间有自动转换Boolean.这是不可能的,myFunc2因为变量的地址被传递,这里DarwinBoolean恰好是Mac Type Boolean.

在以前版本的Swift中 - 如果我没记错的话 - 调用了这个映射类型Boolean,并且DarwinBoolean稍后已重命名.


更多关于ObjCBool: ObjCBool是Objective-C类型的Swift映射BOOL,它可以是signed charC/C++ bool类型,具体取决于体系结构.例如,该NSFileManager方法

- (BOOL)fileExistsAtPath:(NSString *)path
         isDirectory:(BOOL *)isDirectory
Run Code Online (Sandbox Code Playgroud)

被导入到Swift中

func fileExistsAtPath(_ path: String,
      isDirectory isDirectory: UnsafeMutablePointer<ObjCBool>) -> Bool
Run Code Online (Sandbox Code Playgroud)

这里BOOL返回值被Bool自动转换,但(BOOL *)保持为,UnsafeMutablePointer<ObjCBool> 因为它是变量的地址.