Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare metatype that is a subclass and conforms to a protocol in Swift 4

Tags:

swift

swift4

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?

like image 393
Marián Černý Avatar asked Nov 10 '17 20:11

Marián Černý


People also ask

What is Metatype in Swift?

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 .

How do you ensure the adoption of a protocol only by reference type?

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.

How do I add a protocol in Swift?

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.

How many protocols can a Swift class adopt?

Since classes, structures and, enums can conform to more than one protocol, they can take the default implementation of multiple protocols.


1 Answers

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
like image 196
Marián Černý Avatar answered Oct 25 '22 18:10

Marián Černý