了解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
])
}
}
提前感谢任何提示/指导:)
答案 0 :(得分:0)
虽然我不认为这很优雅,但我确实找到了解决这个问题的方法。
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
}
}