微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

什么是Swift中的DarwinBoolean类型

我在一些 Swift代码中写了Boolean而不是Bool,Xcode提供了我用DarwinBoolean替换它.

问题是,DarwinBoolean是什么?

与Bool和ObjCBool​​类型相比有什么区别?
这是什么目的?

简答:

> Bool是真值的本地Swift类型.
> DarwinBoolean是“历史”C类布尔值的Swift映射.
> ObjCBool​​是Objective-C类型BOOL的Swift映射.

您可以在Swift代码中使用Bool,除非其他类型之一
是与现有核心基金会的互操作性所必需的
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)
}

并且是Swift映射的“历史”C类布尔值
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发行说明:

The type Boolean in MacTypes.h is imported as Bool in contexts that
allow bridging between Swift and Objective-C types.

In cases where the representation is significant,Boolean is imported
as a distinct DarwinBoolean type,which is BooleanLiteralConvertible
and can be used in conditions (much like the ObjCBool type).
(19013551)

作为一个例子,功能

void myFunc1(Boolean b);
void myFunc2(Boolean *b);

被导入斯威夫特

public func myFunc1(b: Bool)
public func myFunc2(b: UnsafeMutablePointer<DarwinBoolean>)

在myFunc1中有一个本地的自动转换
Swift类型Bool和Mac类型Boolean.
这在myFunc2中是不可能的,因为变量的地址
被传递,这里DarwinBoolean是Mac Type Boolean.

在以前版本的Swift中 – 如果我记得正确 – 这个映射
类型被称为布尔值,并且稍后已被重命名为DarwinBoolean.

更多关于ObjCBool​​:
ObjCBool​​是Objective-C类型BOOL的Swift映射,
这可以是char或C/C++的bool类型,取决于
建筑.例如NSFileManager方法

- (BOOL)fileExistsAtPath:(Nsstring *)path
         isDirectory:(BOOL *)isDirectory

被导入Swift as

func fileExistsAtPath(_ path: String,isDirectory isDirectory: UnsafeMutablePointer<ObjCBool>) -> Bool

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

原文地址:https://www.jb51.cc/swift/318895.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐