Monday, October 7, 2024

Dealing With Objective-C Protocol Types in Swift

Dave Rahardja:

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 ObjectIdentifiers[…]

[…]

The answer is yes: there is a way to convert a Swift type that refers to an Objective-C protocol into an Objective-C Protocol reference.

[…]

fungibleSwiftProtocol as AnyObject as? Protocol

There is apparently no way to convert in the other direction.

Previously:

1 Comment RSS · Twitter


If only there was

fungibleSwift as AnyFADGarbage as! ObjC

To help us get rid of this ever-growing nightmare of a language.

Leave a Comment