gpt4 book ai didi

swift - GRMustache - 子类上的 MustacheBox

转载 作者:行者123 更新时间:2023-11-30 13:49:48 25 4
gpt4 key购买 nike

了解 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com