Dealing with Objective-C Protocol types in Swift
When Objective-C headers are imported into Swift using a bridging header, a single Objective-C protocol appears as two different entities in Swift code.
Say we have the following Objective-C header file that has been imported into a Swift target using a bridging header:
// Fungible.h
@protocol Fungible<NSObject>
- (NSString *)funge;
@end
There are two ways to refer to this protocol in Swift: using a native Swift type, or using an Objective-C Protocol
object reference.
let fungibleSwiftProtocol = Fungible.self
let fungibleObjCProtocol = NSProtocolFromString("Fungible")!
These two types should be the same—after all, they refer to the same protocol—but they are not, as shown when we print out their descriptions and ObjectIdentifier
s:
print("fungibleSwiftProtocol: \(fungibleSwiftProtocol)")
print("fungibleSwiftProtocol object identifier: \(ObjectIdentifier(fungibleSwiftProtocol))")
print("fungibleObjCProtocol: \(fungibleObjCProtocol)")
print("fungibleObjCProtcol object identifier: \(ObjectIdentifier(fungibleObjCProtocol))")
Which produces the output:
fungibleSwiftProtocol: Fungible
fungibleSwiftProtocol object identifier: ObjectIdentifier(0x00000001f5d8e300)
fungibleObjCProtocol: <Protocol: 0x100008780>
fungibleObjCProtcol object identifier: ObjectIdentifier(0x0000000100008780)
They are different! But of course they’re different, you say: one of them is a Swift Any.Type
, while the other is a Protocol
instance. Sure, but they refer to the same thing. Is there a way to actually test if they refer to the same thing?