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

时间:2022-12-27 16:10:50

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.

这不是In Swift的副本,我如何声明符合一个或多个协议的特定类型的变量?这个问题是关于一个特定的用例,我需要一个元类型,并且如何做到这一点绝对不明显。

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中的协议?

1 个解决方案

#1


10  

To declare a type that is a subclass and conforms to a protocol in Swift 4 you can use this syntax:

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

var classForCell: (UICollectionViewCell & AdditionalHeightable).Type

#1


10  

To declare a type that is a subclass and conforms to a protocol in Swift 4 you can use this syntax:

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

var classForCell: (UICollectionViewCell & AdditionalHeightable).Type