Md. Najmul Hasan Md. Najmul Hasan - 1 month ago 5x
Swift Question

How to represent 'Bool?' in obj c?

I am trying to write a protocol in swift

@objc protocol RestAPIManagerDelegate {

optional func credentialValidated(isValid: Bool?)

But I am getting following error:

'Method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C'

Any suggestion?


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

  • Remove the Optional and just declare that type a Bool

  • Use an object type. For example, declare the type as AnyObject? (or NSNumber?). 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.