MertD MertD - 5 months ago 28
Swift Question

For Loop in Apple Swift

Apple's newly released language Swift has an example on the official documentation. Example is like this;

let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
largest


This is pretty simple but as an extra exercise,it requires to add another variable in order to return what type is the largest number (i.e. Square is the case here)

However, I can't seem to figure out what is "(kind,numbers)" here represent and how should I make my for-loop to go through all Dictionary(interestingNumbers) keys and find which key has the largest number.

Thank you all for your help in advance

Answer

Swift allows you to loop over a dictionary with tuple-syntax (key, value). So in every iteration of the for-loop Swift cares about reassigning the specified tuple-variables (kind and number in your case) to the actual dictionary-record.

To figure out which Key includes the highest number in your example you can extend your code as follows:

let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25],
]

var largest = 0
var largestKey = ""
for (kind, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largest = number
            largestKey = kind
        }
    }
}
largest     // =25
largestKey  // ="Square"

Or if you want to practice the tuple-syntax try that (with the same result):

var largest = 0
var largestKey = ""
for (kind, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            (largestKey, largest) = (kind, number)
        }
    }
}
largest     // =25
largestKey  // ="Square"