2014-12-04 206 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) 
    { 
     ... 
    } 

這是我擺脫了錯誤的方式。

相關問題