深入了解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
])
}
}
在此先感谢您的提示/指导:)
最佳答案
虽然我认为这并不完美,但我确实找到了解决此问题的方法。
创建变量(“ boxedValues”)以从父类导出属性
父项上的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
}
}
关于swift - GRMustache-子类上的mustacheBox,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34424159/