Fayyouz
Fayyouz

Reputation: 682

Iterating through a 3rd degree nested dictionary in swift 4

I have dictionary created by a couple nested dictionaries, that looks like this:

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

I want to iterate between al pf it’s components to get the sum of all the first integers in the tuple (S1), and the sum of all the second integers in the tuple (S2).

Here's the actual code:

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)
        ]
    ]
]

Upvotes: 0

Views: 244

Answers (2)

Alexander
Alexander

Reputation: 63399

Try this:

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
}

Even better, you can just use flatMap and 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

Upvotes: 1

Fayyouz
Fayyouz

Reputation: 682

Found the solution:

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
}

Upvotes: 0

Related Questions