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 允许声明一个变量,它是一个子类并且符合多个协议(protocol):
var myVariable: MyClass & MyProtocol & MySecondProtocol
我需要这样的一致性,但不是为了实例,而是为了类型本身。但对于以下语法:
var classForCell: UICollectionViewCell.Type & AdditionalHeightable.Type
给我这个错误:
Non-protocol, non-class type 'UICollectionViewCell.Type' cannot be used within a protocol-constrained type
如何在 Swift 4 中声明一个子类并符合协议(protocol)的元类型?
最佳答案
要声明一个子类类型并符合 Swift 4 中的协议(protocol),您可以使用以下语法:
var classForCell: (UICollectionViewCell & AdditionalHeightable).Type
关于swift - 声明作为子类并符合 Swift 4 协议(protocol)的元类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47230858/