Reputation: 7711
public protocol Subscriber : class {
}
public struct Subscription {
private weak var subscriber:AnyObject<Subscriber>? = nil
}
Why can't I use AnyObject
with a protocol for this var?
Upvotes: 1
Views: 228
Reputation: 13679
Swift doesn't allow combining a type and a protocol the way Objective-C does, although you can specify a combination of protocols. Since AnyObject
is in fact a protocol, you can accomplish what you want to express above by writing:
public struct Subscription {
private weak var subscriber:protocol<Subscriber, AnyObject>? = nil
}
This requires subscriber
to conform to both the Subscriber
and the AnyObject
protocols.
In your case above, you actually don't need the AnyObject
part since you made the Subscriber
protocol a class
protocol which essentially guarantees that any conforming type is also an AnyObject
. So you could just write:
public struct Subscription {
private weak var subscriber:Subscriber? = nil
}
But the protocol<Subscriber, AnyObject>
approach would allow your Subscriber protocol to not be restricted to only class types, while making that specific subscriber
weak var restricted to class types that implement Subscriber
.
Upvotes: 4
Reputation: 42449
To refer to an object that conforms to a protocol, just use the protocol. Swift is not like Objective-C where you need to specify id<SomeProtocol>
:
public struct Subscription {
private weak var subscriber: Subscriber? = nil
}
You can also declare your protocol like this if you want to restrict usage to AnyObject
, rather than using class
:
public protocol Subscriber : AnyObject {
// ...
}
Upvotes: 2