I'm almost a complete programming beginner and I've started to go through a Swift ebook from Apple.
The things I read are pretty clear, but once you start to experiment things get tricky :).
I'm stuck with the experiment in the Control Flow section. Here is the initial code:
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
And here is the task:
Add another variable to keep track of which kind of number was the largest, as well as what that largest number was.
As I understand, they want me to add up all the values in each number kind (get a total sum for Prime, Fibonacci and Square) and then compare the result to show the largest result. But I can't figure out the syntax.
Can someone share any advice on how to tackle this experiment? Maybe I'm not understanding the problem?
Swift – Iterate through Dictionary To iterate over (key, value) pairs of a Dictionary, use for loop. You can also access the index of the (key, value) paris using the enumerated Dictionaries.
Swift dictionary is made of two generic types: Key (which has to be Hashable ) and Value. An entry can be made by providing a key and its value. A value can be retrieved by providing a key which has been inserted before. A entry can be deleted by providing a key.
There is no order. Dictionaries in Swift are an unordered collection type. The order in which the values will be returned cannot be determined.
Swift dictionary is an unordered collection of items. It stores elements in key/value pairs. Here, keys are unique identifiers that are associated with each value.
They're just asking you to keep track of which number category the largest number belongs to:
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 largestkind = "" for (kind, numbers) in interestingNumbers { for number in numbers { if number > largest { largest = number largestkind = kind } } } largest largestkind
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With