Vik Singh
Vik Singh

Reputation: 1603

Why use class only protocols in Swift?

Can anyone please explain class only protocols to me in Swift. I understand what protocols are and why we use them. I also understand that its recommended to use class only protocols when we use reference type objects in it and want to limit the protocol conformation to classes only. However, I can't find any good answer to support that recommendation. Why is it recommended? What is the drawbacks of using normal protocols in that case.

Upvotes: 5

Views: 961

Answers (2)

user652038
user652038

Reputation:

Another use case used to be to extend reference types to adopt protocols. You can't extend AnyObject itself (to inherit from another protocol, or for any other reason) but you have any reference types you want adopt a protocol inherited from AnyObject.

For example, having class equality based on unique identity is often a perfectly fine solution, so you could adopt EquatableObject:

public protocol EquatableObject: AnyObject, Equatable { }

public extension EquatableObject {
  static func == (class0: Self, class1: Self) -> Bool {
    class0 === class1
  }
}

But now, we have protocol extension constraints (using where clauses), so instead of extending AnyObject, we can extend the protocol, and use AnyObject as a constraint. It looks backwards but operates identically, and removes the need for our own protocol. 🥳

public extension Equatable where Self: AnyObject {
  static func == (class0: Self, class1: Self) -> Bool {
    class0 === class1
  }
}

Upvotes: 0

user102008
user102008

Reputation: 31353

One use case:

  • You have a "delegate" protocol and someone wants to have a weak property of that protocol type. weak can only be used on reference types; therefore, the protocol must be class-only.

Upvotes: 12

Related Questions