我有一个带有自定义
struct ExampleStruct
的 subscript
。 struct data 是一个固定的私有字典,value
。该结构有一个元素Sum
,它本质上是私有字典中其他元素的总和
struct ExampleStruct {
private var value: [String:Double] {
didSet {
value["Sum"] = value.filter{$0.key != "Sum"}.reduce(0.+)
}
}
init(){
value = ["Ind1":12, "Ind2":13, "Sum":25]
}
subscript(index: String) -> Double {
get {
// some error checking too about index
return value[index]
}
set {
value[index] = newValue
}
我想将此结构用作依赖于另一个函数的计算属性,该函数依赖于通过另一个依赖函数具有“Sum”索引的结构的值。 SampleFunc 类似于:
func sampleFunc() -> ExampleStruct {
...
sampleFunc2(sum: exampleImplementation["Sum"])
...
}
我正在使用以下内容,但它是递归的:
var exampleImplementation: ExampleStruct {
return sampleFunc() //sampleFunc depends on exampleImplementation["Sum"]
//func returns ExampleStruct
}
}
但我只需要设置“Sum”以外的索引的函数。所以我想要这样的东西:
var exampleImplementation: ExampleStruct {
if INDEX=="SUM" { //
return SOME BACKING VALUE
} else {
return sampleFunc()[INDEX NOT EQUAL TO "Sum"] //func depends on exampleImplementation["Sum"]
//func returns ExampleStruct
}
}
对于计算属性中具有下标的结构,有没有办法实现此目的?
如果我们忽略不一致的代码,简单地在
set
方法的 subscript
部分添加一个过滤器不就是解决方案吗?
set {
if index == "Sum" { return }
value[index] = newValue
}
我的完整结构版本
struct ExampleStruct {
static let Sum = "Sum"
private var value: [String:Double] {
didSet {
value[Self.Sum] = value.filter{$0.key != Self.Sum}.map(\.value).reduce(0 , +)
}
}
init(){
value = ["Ind1":12, "Ind2":13, "Sum":25]
}
subscript(index: String) -> Double? {
get {
// some error checking too about index
return value[index]
}
set {
if index == Self.Sum { return }
value[index] = newValue
}
}
var sum: Double {
value[Self.Sum, default: 0]
}
}
一个例子
var example = ExampleStruct()
example["Ind1"] = 3
example["Ind2"] = 3
example["Ind3"] = 3
example[ExampleStruct.Sum] = 3
print(example.sum)
9.0