加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

什么是Swift中的DarwinBoolean类型

发布时间:2020-12-14 05:20:58 所属栏目:百科 来源:网络整理
导读:我在一些 Swift代码中写了Boolean而不是Bool,Xcode提供了我用DarwinBoolean替换它. 问题是,DarwinBoolean是什么? 与Bool和ObjCBool??类型相比有什么区别? 这是什么目的? 简答: Bool是真值的本地Swift类型. DarwinBoolean是“历史”C类布尔值的Swift映射.
我在一些 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??>因为它是变量的地址.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读