本文介绍了类型“布尔"不符合协议“布尔类型"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据Apple文档(和),我似乎遇到了麻烦,原因是将Objective-C代码移植到Swift中...在这种情况下,编译器再也没有多余了.

In attempting to create a Launch Helper as per the Apple docs (and tutorial-ized), I seem to be hitting a hiccup caused by porting the Objective-C code into Swift... who's compiler couldn't be any more redundant in this case.

import ServiceManagement

let launchDaemon: CFStringRef = "com.example.ApplicationLauncher"

if SMLoginItemSetEnabled(launchDaemon, true) // Error appears here
{
    // ...
}

错误似乎始终是:

Type 'Boolean' does not conform to protocol 'BooleanType'

我尝试过在多个位置强制转换为Bool,以防万一我只是处理> (由Obj-C或Core Foundation带来),无济于事.

I have tried casting to Bool in a number of locations, in case I'm simply dealing with a redundant, archaic primitive (either brought in by Obj-C or Core Foundation), to no avail.

以防万一,我尝试投射响应:

Just in case, I have tried casting the response:

SMLoginItemSetEnabled(launchDaemon, true) as Bool

会产生错误:

'Boolean' is not convertible to 'Bool'

...认真吗?

推荐答案

Boolean是历史Mac类型",并声明为

Boolean is a "historic Mac type" and declared as

typealias Boolean = UInt8

因此它会编译:

if SMLoginItemSetEnabled(launchDaemon, Boolean(1)) != 0 { ... }


对于Boolean类型具有以下扩展方法(而且我不确定此信息是否已发布过,现在无法找到):


With the following extension methods for the Boolean type(and I am not sure if this has been posted before, I cannot find it right now):

extension Boolean : BooleanLiteralConvertible {
    public init(booleanLiteral value: Bool) {
        self = value ? 1 : 0
    }
}
extension Boolean : BooleanType {
    public var boolValue : Bool {
        return self != 0
    }
}

您可以只写

if SMLoginItemSetEnabled(launchDaemon, true) { ... }

  • BooleanLiteralConvertible扩展名允许自动转换第二个参数trueBoolean.
  • BooleanType扩展名允许Boolean的自动转换if语句将函数的值返回到Bool.
    • The BooleanLiteralConvertible extension allows the automatic conversion ofthe second argument true to Boolean.
    • The BooleanType extension allows the automatic conversion of the Booleanreturn value of the function to Bool for the if-statement.
    • 更新:从 Swift 2/Xcode 7 beta 5开始,历史Mac类型" Boolean映射为Bool到Swift,这使得上述扩展方法已过时.

      Update: As of Swift 2 / Xcode 7 beta 5, the "historic Mac type" Booleanis mapped to Swift as Bool, which makes the above extension methodsobsolete.

      这篇关于类型“布尔"不符合协议“布尔类型"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:03