Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

objective c - Type 'Boolean' does not conform to protocol 'BooleanType'

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
{
    // ...
}

The error seems to consistently be:

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

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

which yields the error:

'Boolean' is not convertible to 'Bool'

...seriously?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...