Expose subset of protocol to Objective-C?

Is it possible to expose a subset of a protocol to Objective-C? @nonobjc does not seem to be permitted. in @objc protocols.

// Goal: expose only `baz` to Objective-C
@objc protocol Foo {
    @nonobjc var bar: Bool { get } // Compile error: Declaration is a member of an @objc protocol, and cannot be marked @nonobjc
    var baz: Bool { get }
}

For my particular use case, I'd like to only expose what is actually expressible in Objective-C. In this example, the optional Bool property cannot be expressed in Objective-C.

@objc protocol Foo {
    var optionalBar: Bool? { get } // Compile error: Property cannot be a member of an @objc protocol because its type cannot be represented in Objective-C
    var baz: Bool { get }
}

Is there any way to hide optionalBar from Objective-C while keeping it in the protocol?

You could define an @objc protocol with your ObjC requirements, then extend it with a Swift protocol that inherits the objc protocol and adds your Swift-only requirements.

2 Likes