【问题标题】:Why extend your own protocol?为什么要扩展你自己的协议?
【发布时间】:2017-02-10 20:59:38
【问题描述】:

我正在浏览 Swift 3 教程和文档,我发现每个人在处理协议时都在使用一种设计模式。它首先声明一个带有少量变量(有时只有一两个变量)的协议,然后创建该协议的扩展并在扩展中定义一些方法。例如(这确实是一个愚蠢的代码示例,仅用于演示):

protocol Bicycle {
    var numberOfWheels: Int {get}
    var isMoving: Bool {get set}
}

extension Bicycle {
    func startPedaling() { isMoving = true }
    func stopPedaing() { isMoving = false }
}

协议和扩展由我完全控制(因为我是开发人员,我可以访问此资源文件)。而且,它们都驻留在同一个资源文件中。

那么,为什么方法驻留在扩展中而不是在原始协议中?例如:

protocol Bicycle {
    var numberOfWheels: Int {get}
    var isMoving: Bool {get set}

    func startPedaling() { isMoving = true }
    func stopPedaing() { isMoving = false }
}

谢谢, 鲍里斯。

【问题讨论】:

标签: swift protocols


【解决方案1】:

也许在您介绍的那种情况下,它可能没有多大意义,但是在某些情况下,您自己的协议的协议扩展非常强大,尤其是当您使用约束时,哪个类获得了扩展。

想象一下下面的例子。如果 bicicle 是山地自行车,我会添加类似“指南针”(不是最好的例子)的东西。然后我会做以下事情:

protocol Bicycle {
    var numberOfWheels: Int {get}
    var isMoving: Bool {get set}

extension Bicycle {
    func startPedaling() { isMoving = true }
    func stopPedaing() { isMoving = false }
}

extension Bicycle where Self: MountainBike {
    var compass: Compass {get}
}

class MountainBike: Bicycle {
    //Here you can use the compass
}

class NormalBike: Bicycle {
    //Here you can't use the compass
}

你看到了吗?您可以为每个类添加特定的东西,因此可以针对某些类对协议进行一些调整。现在每个继承自 MountainBike 的类都可以使用指南针。

在这种情况下,它可能很简单,好处也不是那么大,但在某些情况下它可能真的很有用,例如

protocol Controller {
    //some useful variables
}

extension Controller where Self: UIViewController {
    // Here you can use all the properties of a UIViewController
    // like getting the navigation controller, etc. Every
    // UIViewController subclass (or a UIViewController itself)
    // that conforms to it would get this methods
}

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-22
    相关资源
    最近更新 更多