Swift equivalent of id<MyProtocol>?
Asked Answered
A

5

8

The question is in the title. In Objective-C, if I want to have a property (like a delegate) that HAS to adhere to a certain protocol it can be defined like so:

@property (weak) id<MyDelegate> delegate;

How can I do this in Swift?

Addams answered 18/5, 2015 at 17:3 Comment(1)
D
21

A protocol is a type, so you can use it as a declared variable type. To use weak, you must wrap the type as an Optional. So you would say:

weak var delegate : MyDelegate?

But in order for this to work, MyDelegate must be an @objc or class protocol, in order to guarantee that the adopter is a class (not a struct or enum, as they cannot be weak).

Dispersive answered 18/5, 2015 at 17:14 Comment(1)
And see my book for more about this: apeth.com/swiftBook/…Dispersive
P
1

I think the exact oposite is:

weak var delegate: protocol<MyDelegate>?

I prefer this old, objc, style over the swift syntax because in swift first is the base class and then all the adopted protocols. This may be confusing in case your protocol does not have "Delegate" suffix as you won't know whether DataAdoption(for example) is super class or a protocol.

Protractile answered 18/5, 2015 at 17:23 Comment(1)
This was deprecated in Swift 4 :-(Feu
S
0

Use the protocol like a type, so:

weak var delegate:MyDelegate?
Shrewmouse answered 18/5, 2015 at 17:14 Comment(1)
Weak variables must always be of optional type.Strohl
I
0

It is also good to know the equivalent for the Objective-C id<MyProtocolName> in the method declaration in Swift is protocol<MyProtocolName>. For Example:

// Objective-C
-void myMethodWithSome:(id <MyProtocolName>)param {
   // ...
}

// Swift
func myMethodWithSome(param: protocol<MyProtocolName>) {
   //...
}
Iatric answered 19/9, 2015 at 11:13 Comment(0)
S
0

Update for method declarations

Objective-C

-void myMethodWithSome:(id <MyProtocolName>)param {
   // ...
}

Swift

func myMethodWithSome(param: MyProtocolName) {
   //...
}
Sheelah answered 13/8, 2021 at 21:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.