Swift and Boolean

2019-07-17 11:07发布

问题:

The function AUGraphIsInitialized is defined like this:

func AUGraphIsInitialized(inGraph: AUGraph, outIsInitialized: CMutablePointer<Boolean>) -> OSStatus

So, you call it like this:

var status : OSStatus = OSStatus(noErr)
var outIsInitialized:Boolean = 0
status = AUGraphIsInitialized(self.processingGraph, &outIsInitialized)

That works. But how do you check it?

Boolean is defined as an CUnsignedChar (in MacTypes.h)

So, you cannot do this:

if outIsInitialized {
    // whatever
}

And you cannot cast it (could not find an overload...)

var b:Bool = Bool(outIsInitialized)

or with Swift's "as"

var b:Bool = outIsInitialized as Bool

So, my question is: how do you use Boolean in Swift?

回答1:

C represents the Boolean value true with a nonzero value and false with a zero value, so you can just test outIsInitialized against 0:

if outIsInitialized != 0 {
    // outIsInitialized is true
}