ios - Swift 协议(protocol) Where Constraint with == vs :

标签 ios protocols swift4

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

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 可用,其 VechicalTypeHeavyVehical。 这就是为什么你不能在 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/

相关文章:

ios - 创建可读 JSON 字符串的最简单方法是什么?

objective-c - 当我解析 json 时,它会将所有内容都变成 nil

iphone - 圆弧错误 : receiver type for instance message does not declare a method with selector

objective-c - 应用程序在设备上启动时崩溃,但在模拟器上很好

ios - 视网膜 4 中的背景图像

node.js - 如何让多个 Node.js 命令行进程相互通信?

ios - 无法分配给属性 : 'outputs' is a get-only property

iphone - 带有正文参数的 ASIHttpRequest DELETE 方法

windows - 使用自定义协议(protocol)打开 URL - 语法错误?

iOS:针对 iOS 9 时使用 Swift 4