11
votes

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?

1

1 Answers

20
votes

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