ios - 使用 == vs 约束的 Swift 协议:
问题描述
我有以下代码(请忽略拼写错误:))
protocol Vehical {
var wheelsCount:Int {get}
}
protocol LightVehical:Vehical {
func tankWithPetrol (liters:Int)
}
protocol HeavyVehical:Vehical {
func tankWithDisel(liters:Int)
}
protocol OwnsVehical {
associatedtype VechicalType = Vehical
var vehical:VechicalType {get}
}
// Here I have == for constraint
extension OwnsVehical where VechicalType == HeavyVehical {
func fillTankWithDisel() {
}
}
// Light Vehicle
struct VolVOV90 : LightVehical {
var wheelsCount: Int = 4
func tankWithPetrol(liters: Int) {
}
}
// Heavy Vehicle
struct Van : HeavyVehical {
func tankWithDisel(liters: Int) {
}
var wheelsCount: Int = 6
}
struct PersonWithHeavyVehical:OwnsVehical {
typealias VechicalType = Van
let vehical = Van()
}
现在当我尝试
let personWithHeavyV = PersonWithHeavyVehical()
personWithHeavyV.fillTankWithDisel() // It is not compiling with ==
如果我改变
extension OwnsVehical where VechicalType == HeavyVehical
和
extension OwnsVehical where VechicalType : HeavyVehical
代码编译成功我没有找到==和之间的差异:任何人都可以帮助我理解它提前谢谢
解决方案
当你这样做时:
extension OwnsVehical where VechicalType == HeavyVehical
你告诉编译器VechicalType
必须是HeavyVehical 类型。这意味着该方法仅适用fillTankWithDisel
于. 这就是你不能调用的原因,因为不是 a ,而是 a 。OwnsVehical
VechicalType
HeavyVehical
fillTankWithDisel
personWithHeavyV
personWithHeavyV
HeavyVehical
Van
当你这样做时:
extension OwnsVehical where VechicalType : HeavyVehical
您告诉编译器VechicalType
符合协议HeavyVehical
,因此您可以调用,personWithHeavyV.fillTankWithDisel
因为personWithHeavyV
通过符合OwnsVehical
,没有进一步限制,可以调用fillTankWithDisel
.
如果要personWithHeavyV.fillTankWithDisel()
编译,则必须将结构 PersonWithHeavyVehical 的实现更改为以下内容:
struct PersonWithHeavyVehical: OwnsVehical {
typealias VechicalType = HeavyVehical
let vehical = Van()
}
现在你有一个personWithHeavyV
其 VechicalType 是一个HeavyVehical
因此允许你调用所需的方法。
推荐阅读
- python - 如何下载 Python 的 graphics.py?
- ios - 根据所选行显示不同数据的 UIPICKERVIEW
- javascript - 触发事件后将查询字符串传递给 react-router 中的 url
- typescript - 如何让 npm 从 GitHub url 安装 typescript 依赖项?
- android - actionLayout 不显示在导航抽屉中
- android - 试图在列表视图的末尾加载更多项目
- batch-file - 检查驱动器是否有足够的空间进行备份
- android - 应用程序在模拟器上完美显示,但在设计预览中不显示?
- python - 如何从 colaboratory 下载此模型
- installshield - Installshield 2013 Installscript MSI:修复期间错误的 .msi 位置