M
M
MarsFM2018-04-03 14:30:06
iOS
MarsFM, 2018-04-03 14:30:06

How to loop through an array of dictionaries in swift?

Plz tell me how to do it right!

[ [["HomeTeam": "0", "GuestTeam": "0"], ["HomeTeam": "0", "GuestTeam": "0"]],
 [["HomeTeam": "0", "GuestTeam": "0"], ["HomeTeam": "0", "GuestTeam": "0"]],
 [["HomeTeam": "0", "GuestTeam": "0"], ["HomeTeam": "0", "GuestTeam": "0"]] ]

There is a two-dimensional array of dictionaries, I need to get the keys in the order in which they are in the array. You only need to get HomeTeam , but it returns either HomeTeam or GuestTeam .
5ac3659400451701666596.png
for (country, gol) in games[indexPath.section].groups[indexPath.row] {
            cell.countryHome.text = country
            cell.golsHometeam.text = gol
 }

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
V
Vyacheslav Beltyukov, 2018-04-04
@sportredwhite

Unfortunately, you chose the wrong data structure. Your problem is that your code is not iterating over dictionaries, but rather iterating over the contents inside the dictionary. Here you need to know that the order of entries in the dictionary is not guaranteed. That is, when real data appears in the place of HomeTeam and GuestTeam, you will not be able to determine who is who.
I don’t know the source of your data and where they are still used, but purely for this task I would recommend the following structure:

typealias ResultsArray = [[(homeTeam: (name: String, score: String), guestTeam: (name: String, score: String))]]

//для сравнения, ваша структура:
typealias YourStructure = [[[String: String]]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question