【问题标题】:Swift Struct idiom to replace OOP Type Inheritance Pattern?Swift Struct 成语替换 OOP 类型继承模式?
【发布时间】:2018-08-07 21:36:58
【问题描述】:

假设我有一个可以处理 Rectangles 的程序(这是我的实际问题的简化示例),我将其建模为

struct Rectangle {
    let left:Int
    let right:Int
    let top:Int
    let bottom:Int

    func rationalized() -> Rectangle {
        return Rectangle(left: min(self.left, self, right), right: max(self.left, self.right), top: min(self.top, self.bottom)
    }
}

一个合理化的矩形,基本上是一个具有正宽度和高度的矩形。对于许多操作(例如缩放、平移、联合、相交等),最好保证矩形是合理化的。事实上,可以在init(...) 中实习合理化逻辑,这样您就永远无法创建一个不合理的逻辑。但是在某些情况下,您可能希望支持非理性构造,至少是暂时的,可能是为了在拖放期间进行编辑,例如

      func replacing(left newValue:Int) -> Rectangle {
          return Rectangle(left: newValue, right: self.right, top: self.top, bottom: self.bottom)
      }

想要这样做会导致将合理化逻辑放在 init() 中会适得其反。

但另一种方法是使用rationalized() 调用几乎在任何地方(拖放站点除外)乱扔我的代码。我正在尝试确定是否可以以某种方式使用结构和类型来做到这一点。

如果我使用类,我可以有一个 Rectangle 超类和一个 RationalizedRectangle 子类,其中 RationalizedRectangle 覆盖 init 来完成工作。然后我通常可以使用 RationalizedRectangles(甚至在适当的时候将其指定为类型),但允许通过使用 Rectangle 来编辑它们,并在最后转换为 RationalizedRectangle。

但是 Swift 结构体不支持继承。所以我不知道如何惯用地实现这一点。我可以在结构中添加一个 isRationalizing:Boolean 并在其上进行分支,但这看起来很俗气。

是否有一个基于结构的习语可以在这里使用?

【问题讨论】:

  • 好吧,你为什么不创建两个初始化器呢?还是两个结构?例如,通用功能可以移动到协议中。

标签: swift swift-structs


【解决方案1】:

您应该能够使用协议来完成此操作。您可以将通用逻辑移动到协议中,然后使用不同的初始化程序创建两个符合该协议的类。然后,在您引用特定对象类型的地方,您可以改为引用协议。

protocol RectangleProtocol {
    var left:Int {get}
    var right:Int {get}
    var top:Int {get}
    var bottom:Int {get}
}

struct Rectangle: RectangleProtocol {
    let left: Int
    let right: Int
    let top: Int
    let bottom: Int

    init(leftValue:Int, rightValue:Int, topValue:Int, bottomValue:Int) {
        self.left = leftValue
        self.right = rightValue
        self.top = topValue
        self.bottom = bottomValue
    }
}

struct RationalRectangle: RectangleProtocol {
    let left: Int
    let right: Int
    let top: Int
    let bottom: Int

    init(leftValue:Int, rightValue:Int, topValue:Int, bottomValue:Int) {
        self.left = min(leftValue, rightValue)
        self.right = max(leftValue, rightValue)
        self.top = min(topValue, bottomValue)
        self.bottom = max(topValue, bottomValue)
    }
}

let rectangle: RectangleProtocol = Rectangle(leftValue: 4, rightValue 4, topValue: 8, bottomValue: 8)
let rationalRectangle: RectangleProtocol = RationalRectangle(leftValue: 4, rightValue:8, topValue: 7, bottomValue: 4)

// Now both of these represent a struct that conforms to the RectangleProtocol.

【讨论】:

  • 唯一看起来很糟糕的是,我最终将所有其余的行为(翻译等)作为 RectangleProtocol 的扩展。我猜这没关系。我刚刚制定或看到了“行为重”协议。也许那没关系?
  • Swift 是一种面向协议的语言,所以应该没问题。这个想法是,您实现的扩展行为基本上是为协议中的可选属性/方法(或附加功能)提供默认实现。
猜你喜欢
  • 2013-02-19
  • 2021-06-25
  • 1970-01-01
  • 2012-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多