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?
A metatype type refers to the type of any type, including class types, structure types, enumeration types, and protocol types. The metatype of a class, structure, or enumeration type is the name of that type followed by .
You can limit protocol adoption to class types (and not structures or enumerations) by adding the AnyObject or class protocol to a protocol's inheritance list.
To create a protocol, use the protocol keyword followed by the name you want and defined by the curly braces. Protocols can be of 2 types: read-only/read-write. Read-only means you can only get the variable, but you cannot set it. Read-write means you can both set and get properties.
Since classes, structures and, enums can conform to more than one protocol, they can take the default implementation of multiple protocols.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With