Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift for-in loop dictionary experiment

Tags:

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?

like image 986
al_x13 Avatar asked Jun 09 '14 07:06

al_x13


People also ask

Can you loop through a dictionary in Swift?

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.

How are dictionaries implemented in Swift?

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.

Is Swift dictionary ordered?

There is no order. Dictionaries in Swift are an unordered collection type. The order in which the values will be returned cannot be determined.

What is dictionary and write syntax in Swift?

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.


1 Answers

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 
like image 159
Dash Avatar answered Nov 07 '22 14:11

Dash