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?
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?
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
).
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.
Use the protocol like a type, so:
weak var delegate:MyDelegate?
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>) {
//...
}
Update for method declarations
Objective-C
-void myMethodWithSome:(id <MyProtocolName>)param {
// ...
}
Swift
func myMethodWithSome(param: MyProtocolName) {
//...
}
© 2022 - 2024 — McMap. All rights reserved.