Mistah_Sheep Mistah_Sheep - 29 days ago 6
Swift Question

Get top level index from a nested for function

I have an array of arrays of integers (which is an

[[Int]]
) that represents any given month of the year (sections are weeks and rows are days so month[0][2] would return a
3
if you have a month that starts on a Sunday) I am trying to traverse through the array and find a date and then have it return an IndexPath but I am having trouble. So far I have this:

for (index, week) in monthInfo.enumerated() {
for (index, day) in week.enumerated() {
if day == dateComponents.day /* Today's Date (the day I'm looking for) */ {
selectedDay = IndexPath(row: index, section: ???)
}
}
}


I know I can get the index of the day from this but I am not sure how to get the index of the week so that I can make a full IndexPath. Any suggestions? Or even better, how to do this better?

Answer

Since you are in control of your tuples, you can rename index in one or in both of them to disambiguate:

for (indexWeek, week) in monthInfo.enumerated() {
    for (indexDay, day) in week.enumerated() {
        if day == dateComponents.day /* Today's Date (the day I'm looking for) */ {
            selectedDay = IndexPath(row: indexDay, section: indexWeek)
        }
    }
}
Comments