我有以下代码(请忽略拼写错误:))
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
代码编译成功我没有发现==和之间的区别:任何人都可以帮助我理解它提前致谢
最佳答案
当你这样做时:
扩展名 OwnsVehical,其中 VechicalType == HeavyVehical
您是在告诉编译器 VechicalType
必须 是 HeavyVehical 类型。这意味着方法 fillTankWithDisel
将仅对 OwnsVehical
可用,其 VechicalType
是 HeavyVehical
。
这就是为什么你不能在 personWithHeavyV
上调用 fillTankWithDisel
因为 personWithHeavyV
不是 HeavyVehical
,它是 面包车
。
当你这样做时:
扩展名 OwnsVehical,其中 VechicalType : HeavyVehical
你告诉编译器 VechicalType
符合 HeavyVehical
协议(protocol),因此你可以调用 personWithHeavyV .fillTankWithDisel
因为personWithHeavyV
,通过符合OwnsVehical
,没有进一步的限制,可以调用fillTankWithDisel
。
如果您希望 personWithHeavyV.fillTankWithDisel()
进行编译,您必须将结构 PersonWithHeavyVehical 的实现更改为以下内容:
struct PersonWithHeavyVehical: OwnsVehical {
typealias VechicalType = HeavyVehical
让车辆=货车()
}
现在您有一个 personWithHeavyV
,其 VechicalType 是一个 HeavyVehical
,因此您可以调用所需的方法。
关于ios - Swift 协议(protocol) Where Constraint with == vs :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51667614/