简体   繁体   English

声明作为子类的metatype并符合Swift 4中的协议

[英]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? 这不是In Swift的副本, 我如何声明符合一个或多个协议的特定类型的变量? . 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: Swift 4允许声明一个变量,它是一个子类并符合多个协议:

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 非协议,非类型类型'UICollectionViewCell.Type'不能在协议约束类型中使用

How can I declare a metatype that is a subclass and conforms to a protocol in Swift 4? 如何声明作为子类的元类型并符合Swift 4中的协议?

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

var classForCell: (UICollectionViewCell & AdditionalHeightable).Type

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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