Existing any and objective C based protocols

So in pure swift code it is clear to me that if we have a protocol:

protocol Transaction {
    func debit(money: Double)
    func credit(money: Double)

And a structure confirming it:

struct ChequeTransaction: Transaction {
    func debit(money: Double) {
        print("Debiting money: \(money) by Cheque")

func credit(money: Double) {
        print("Crediting money: \(money) by Cheque")

Then if we are declaring a variable with type Transaction we need to be clear about it being existential type by using any:

let transaction: any Transaction = ChequeTransaction()

Now my question is: what if we have Transaction as objective-c protocol:

@protocol Transaction <NSObject>
- (void)creditMoney:(double)money;
- (void)debitMoney:(double)money;

Then also will the below code be meaningful in Swift file?

let transaction: any Transaction = ChequeTransaction()

Let me know if I am missing anything over here.

"any" is not necessary in this case, as the protocol doesn't have self or associated type requirement.

Should be fine (with or without any in this case).

Note that as written in your obj-c the method would be "creditMoney(_ money: Double)" in swift, to make it "credit(money: Double)" you'd need to change the prototype slightly in obj-c header:

@protocol Transaction <NSObject>
- (void)creditMoney:(double)money NS_SWIFT_NAME(credit(money:));
- (void)debitMoney:(double)money NS_SWIFT_NAME(debit(money:));
1 Like

Not yet, but the using a bare protocol name as an existential is planned to be removed at some point (Swift 6 IIRC), so it's better to get into the habit of not using it.

You can still extend an imported ObjC protocol in Swift to use Self in consuming position in extension methods, and you would not be able to use those methods on any types.

It's very tempting to go down the path of wanting to distinguish between protocols with Self or associated type requirements with ones that don't, but that path is exactly what has lead to so much confusion about existential types and why the semantics suddenly change as soon as you add such a requirement to an existing protocol.