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

半城伤御伤魂 提交于 2019-11-28 01:51:53

Boolean is a "historic Mac type" and declared as

typealias Boolean = UInt8

so this compiles:

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

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
    }
}

you can just write

if SMLoginItemSetEnabled(launchDaemon, true) { ... }
  • The BooleanLiteralConvertible extension allows the automatic conversion of the second argument true to Boolean.
  • The BooleanType extension allows the automatic conversion of the Boolean return value of the function to Bool for the if-statement.

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

Right, I had a similar issue trying to get the BOOL return of an objective-C method in Swift.

Obj-C:

- (BOOL)isLogging
{
    return isLogging;
}

Swift:

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

this was the way that I got rid of the error.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!