swift - 声明作为子类并符合 Swift 4 协议(protocol)的元类型

标签 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 允许声明一个变量,它是一个子类并且符合多个协议(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/

相关文章:

swift - 如果使用从右到左的语言,String.prefix() 是否像 String.suffix 一样工作?

ios - 连接两个 strokeEnd 动画

ios - 使用 DragGesture 调整 SwiftUI View 的框架会在所有维度上调整其大小

ios - UITableViewCell 行为奇怪 - 文本变为白色

Swift:通用协议(protocol)无法使用类型的参数列表调用

swift - cccrypt 在 swift 4 中生成奇怪的输出

ios - 如何将滑出/汉堡菜单合并到现有的标签栏 Controller

ios - swift 中文本字段的前景色

swift - 将字典传递给 init 方法

swift - spriteKit didBeginContact 无法添加Child