gpt4 book ai didi

swift - 在 swift 4 中迭代三级嵌套字典

转载 作者:行者123 更新时间:2023-11-28 14:35:40 26 4
gpt4 key购买 nike

我有几个嵌套字典创建的字典,看起来像这样:

var apartments: [Block : [Floor : [Side : (Int, Int) ]]

我想在 al pf it's components 之间迭代以获得元组 (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)
]
]
]

最佳答案

试试这个:

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
}

更好的是,您可以只使用flatMapreduce:

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

关于swift - 在 swift 4 中迭代三级嵌套字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50918593/

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