11

This is NOT a duplicate of In Swift, how can I declare a variable of a specific type that conforms to one or more protocols?. This question is about a specific use case where I needed a metatype and it was definitely not obvious how to do it.

Swift 4 allows declaring a variable that is a subclass and conforms to multiple protocols:

var myVariable: MyClass & MyProtocol & MySecondProtocol

I need such conformance but not for the instances but for the type itself. But for the following syntax:

var classForCell: UICollectionViewCell.Type & AdditionalHeightable.Type

gives me this error:

Non-protocol, non-class type 'UICollectionViewCell.Type' cannot be used within a protocol-constrained type

How can I declare a metatype that is a subclass and conforms to a protocol in Swift 4?

Marián Černý
  • 15,096
  • 4
  • 70
  • 83

1 Answers1

20

To declare a type that is a subclass and conforms to a protocol in Swift 4 you can use this syntax:

var classForCell: (UICollectionViewCell & AdditionalHeightable).Type
Marián Černý
  • 15,096
  • 4
  • 70
  • 83
  • I'm answering my own question but it took me hours to find this out. Hope this would be helpful to somebody. I was playing with generics, where this can be expressed as well, but it was limited in other ways. – Marián Černý Nov 10 '17 at 20:53
  • Please mark it as a correct answer, even though it is your solution to your question. – Luzo Nov 10 '17 at 21:38
  • Somewhat surprised that such code even compiles, let alone works! The Swift compiler team might be onto something here... ;) – Paulo Mattos Nov 11 '17 at 04:10
  • When I try to assign the variable as a delegate I get this error: `Cannot assign value of type '(UIViewController & ExperienceDelegate).Type' to type 'ExperienceDelegate?'` Any idea how to deal with this one? – Hadi Sharghi Dec 03 '18 at 06:19
  • You are assigning a type where an instance is expected. You probably don't need `(UIViewController & ExperienceDelegate).Type` in your case, but straightforward `UIViewController & ExperienceDelegate`. – Marián Černý Dec 03 '18 at 09:53
  • Thank you so much for finding this solution!!!! saved me hours. – pizza7 Jan 22 '20 at 02:59