简体   繁体   中英

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

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?

要声明一个子类型并符合Swift 4中的协议,您可以使用以下语法:

var classForCell: (UICollectionViewCell & AdditionalHeightable).Type

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM