GRMustache - 子类上的mustacheBox

时间:2015-12-22 20:45:47

标签: swift mustache

了解GRMustache和Swift。

如果我有一个父类实现MustacheBoxable的类和子类,是否可以在子节点上扩展mustacheBox而不重复mustacheBox的整个变量设置?

class Host: MustacheBoxable {
  var name: String?
}
extension Host {
    var mustacheBox: MustacheBox {
      return Box([
         "name": self.name
      ])
    }
}

class TopGearHost: Host {
  var drives_slowly: Bool = false
}
extension Host {
    var mustacheBox: MustacheBox {
      //how would I go about NOT doing this?
      return Box([
          "name": self.name,  // don't want to repeat this guy
          "drives_slowly": self.drives_slowly
      ])
    }
}

提前感谢任何提示/指导:)

1 个答案:

答案 0 :(得分:0)

虽然我不认为这很优雅,但我确实找到了解决这个问题的方法。

       
  • 创建变量(" boxedValues"),用于从父类导出属性    
  • parent上的mustacheBox返回盒装变量    
  • 然后,子类可以访问父类(" boxedValues")变量并添加值    
  • mustacheBox的实现只是继续为子类工作
class Host: MustacheBoxable {
    var name: String?
}
extension Host {
    var boxedValues: [String:MustacheBox] {
        return [ "name" : self.name ]
    }
    var mustacheBox: MustacheBox {
        return Box(boxedValues)
    }
}
class TopGearHost: Host {
    var drives_slowly: Bool = false
}
extension Host {
    override var boxedValues: [String:MustacheBox] {
        var vals = super.boxedValues
        vals["drives_slowly"] = Box(self.drives_slowly)
        return vals
    }
}