首页 > 解决方案 > 使用 == 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 

代码编译成功我没有找到==和之间的差异:任何人都可以帮助我理解它提前谢谢

标签: iosprotocolsswift4

解决方案


当你这样做时:

extension OwnsVehical where VechicalType == HeavyVehical

你告诉编译器VechicalType 必须是HeavyVehical 类型。这意味着该方法仅适用fillTankWithDisel于. 这就是你不能调用的原因,因为不是 a ,而是 a 。OwnsVehicalVechicalTypeHeavyVehicalfillTankWithDiselpersonWithHeavyVpersonWithHeavyVHeavyVehicalVan

当你这样做时:

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因此允许你调用所需的方法。


推荐阅读