How to represent an optional Bool (Bool?) in Objective-C?
The problem is this type declaration:
`isValid: Bool?`
That is perfectly fine in Swift. But you cannot expose it to Objective-C, because Objective-C does not have any notion of an Optional BOOL - a BOOL in Objective-C is basically just a number, a primitive C datatype (what we call a scalar).
Here's another way of looking at it. In an interchange with Objective-C, you can use a Swift Optional anywhere that Objective-C can say nil
- indeed, to a large extent Swift Optional exists exactly in order to deal with the possibility that Objective-C will say nil
or that you might need to say nil
to Objective-C. But a BOOL in Objective-C can never be nil
- it can only be YES or NO (Swift true
or false
).
So you have three choices:
Take away the
@objc
that exposes all this to Objective-CRemove the Optional and just declare that type a Bool
Use an object type. For example, declare the type as
AnyObject?
(orNSNumber?
). This will work because Swift will bridge a Bool to an NSNumber (including as it passes into an AnyObject), and Objective-C will deal just fine with an Optional AnyObject or Optional NSNumber because those are object types, not scalars.
Object-C does not have the concept of optionals, try to remove the "?" from your declaration