带有== vs约束的Swift协议:

时间:2018-08-03 07:41:56

标签: ios protocols swift4

我有以下代码(请忽略拼写错误:))

SimpleDateFormat

现在当我尝试

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 

代码编译成功,我没有找到==和之间的区别。:任何人都可以帮助我理解它。

2 个答案:

答案 0 :(得分:2)

当您这样做:

extension OwnsVehical where VechicalType == HeavyVehical

您要告诉编译器VechicalType 必须是HeavyVehical类型。这意味着方法fillTankWithDisel仅对OwnsVehicalVechicalType的{​​{1}}可用。 这就是为什么您无法在HeavyVehical上调用fillTankWithDisel的原因,因为personWithHeavyV不是personWithHeavyV,而是HeavyVehical

当您这样做:

Van

您要告诉编译器extension OwnsVehical where VechicalType : HeavyVehical 符合符合VechicalType协议,因此您可以调用HeavyVehical,因为{{1} },只要遵守personWithHeavyV.fillTankWithDisel,就没有其他限制,可以调用personWithHeavyV

如果您希望OwnsVehical进行编译,则必须将结构PersonWithHeavyVehical的实现更改为以下内容:

fillTankWithDisel

现在您有一个personWithHeavyV.fillTankWithDisel(),其VechicalType是struct PersonWithHeavyVehical: OwnsVehical { typealias VechicalType = HeavyVehical let vehical = Van() },因此可以调用所需的方法。

答案 1 :(得分:0)

  1. ==运算符

    ==运算符检查其实例值是否相等,"equal to"  //因此您在这里比较VechicalType == HeavyVehical并返回false

  2. :运算符

    :是指定义变量的类型 为此,您可以检查此link