Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get key and value from dictionary of objects in Swift?

Can anyone help me out on printing the key-values from this array to the console?

I am able to loop over the array and print out a value when I give the key-name. But I do not have an idea how to loop over the key-values aswel.

var tableDataGates : [[String:String]] = [
      ["TopTitle" : "Gate A1", "MiddleText" : "Lissabon", "MiddleTextExtra" : "15:15","BottomText" : "Check-in opens at", "BottomTextExtra" : "15:00", "TimeToEndPoint" : "10"]
]

for x in 0 ..< tableDataGates.count {
    print(tableDataGates[x]["TopTitle"]); //PRINTS "GATE A1"
}

Thanks in advance

like image 423
UserUser123 Avatar asked Dec 28 '25 13:12

UserUser123


1 Answers

You can do it this way:

var tableDataGates : [[String:String]] = [
    ["TopTitle" : "Gate A1", "MiddleText" : "Lissabon", "MiddleTextExtra" : "15:15","BottomText" : "Check-in opens at", "BottomTextExtra" : "15:00", "TimeToEndPoint" : "10"]
]

for gate in tableDataGates {
    for (key, value) in gate {
        print("\(key): \(value)")
    }
}

which outputs:

MiddleText: Lissabon
TimeToEndPoint: 10
TopTitle: Gate A1
BottomTextExtra: 15:00
BottomText: Check-in opens at
MiddleTextExtra: 15:15
like image 69
Crowman Avatar answered Dec 31 '25 07:12

Crowman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!