2014-12-04 100 views
10

在试图创建一个启动辅助按照苹果文档(和tutorial-ized),I似乎击打引起的移植Objective-C代码到夫特打嗝。在这种情况下,谁的编译器不能再多余。类型“布尔”不符合协议“BooleanType”

import ServiceManagement 

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

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

的错误似乎始终是:

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

我曾尝试在多个位置铸造Bool,如果我只是一个redundant, archaic primitive处理(通过引进Obj-C或Core Foundation),无济于事。

以防万一,我已经试过铸造响应:

SMLoginItemSetEnabled(launchDaemon, true) as Bool

其产生错误:

'Boolean' is not convertible to 'Bool'

...重视呢?

+0

亲爱的克里斯,你可以添加我的Skype:[email protected]&帮我实施SMLoginItemSetEnabled。我现在在线。非常感谢。 – 2015-06-01 07:48:24

回答

17

Boolean是一个 “历史性的苹果型”,并宣布为

typealias Boolean = UInt8 

所以这个编译:

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

用下面的扩展方法为Boolean型 (和我不知道这是否已经发布之前,我现在找不到它):

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

更新:作为夫特2/Xcode的7测试5, “历史性MAC类型” Boolean 被映射到快速作为Bool,这使得上述的扩展方法 过时。

+0

嘿,我喜欢'布尔(1)' - 使它更容易理解您打电话给它。 :) – 2014-12-04 21:30:52

+1

@NateCook:好的,恢复,谢谢! – 2014-12-04 21:31:43

+0

本来可以发誓我试过这个组合......虽然它有效!谢谢! – 2014-12-04 21:31:58

0

对,我有一个类似的问题,试图让BOOL在Swift中返回一个Objective-C方法。

的OBJ-C:

- (BOOL)isLogging 
{ 
    return isLogging; 
} 

斯威夫特:

if (self.isLogging().boolValue) 
    { 
     ... 
    } 

这是我摆脱了错误的方式。

相关问题