我有几个嵌套字典创建的字典,如下所示:
var apartments: [Block : [Floor : [Side : (Int, Int) ]]
我想在al pf it的组件之间迭代,得到元组中所有第一个整数的总和(S1),以及元组中所有第二个整数的总和(S2)。
这是实际的代码:
enum Side {
case right
case left
}
enum Floor {
case GF
case FirstFloor
case Duplex
}
enum Block {
case A
case B
case C
case D
}
var apartments: [Block : [Floor : [Side : (Int, Int) ]]] = [
.A: [
.GF: [
.right: (33, 140),
.left: (33, 140)
],
.FirstFloor: [
.right: (36, 150),
.left: (36, 150)
],
.Duplex: [
.right: (50, 210),
.left: (50, 210)
]
],
.B: [
.GF: [
.right: (33, 140),
.left: (33, 140)
],
.FirstFloor: [
.right: (36, 150),
.left: (36, 150)
],
.Duplex: [
.right: (50, 210),
.left: (50, 210)
]
],
.C: [
.GF: [
.right: (33, 133),
.left: (38, 148)
],
.FirstFloor: [
.right: (36, 141),
.left: (39, 153)
],
.Duplex: [
.right: (50, 200),
.left: (58, 225)
]
],
.D: [
.GF: [
.right: (38, 140),
.left: (38, 140)
],
.FirstFloor: [
.right: (39, 146),
.left: (39, 146)
],
.Duplex: [
.right: (58, 214),
.left: (58, 214)
]
]
]
答案 0 :(得分:1)
试试这个:
func sum() -> Int {
var x = 0
for (block, floors) in apartments {
for (floor, sides) in floors {
for (side, FOO) in sides { // idk what the value here is. Rename FOO
x += FOO
}
}
}
return x
}
更好的是,您可以使用flatMap
和reduce
:
func sum(_ apartments: [Block : [Floor : [Side : (Int, Int) ]]]) -> Int {
return apartments
.values
.lazy
.flatMap { $0.values }
.flatMap { $0.values }
.flatMap { $0.0 }
.reduce(0, +)
}
print(sum(apartments)) // => 1000
答案 1 :(得分:0)
找到解决方案:
func sum() -> Int {
var x = 0
for (block, _) in apartments {
for (floor, _) in apartments[block]! {
for (side, _) in apartments[block]![floor]! {
x += apartments[block]![floor]![side]!.0
}
}
}
return x
}