Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The Swift Programming Language Book Chapter Section on Control Flow Experiment 3

Tags:

ios

swift

I am working through the first chapter of the book and can't figure out the experiment:

Add another variable to keep track of which kind of number was the largest, as well as what that largest number was.

This is the code from the book:

let interstingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13, 17],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25, 36],
]
var largest = 0
for (kind, numbers) in interstingNumbers {
    for number in numbers {
        if number > largest {
            largest = number
        }
    }
}
largest
like image 255
user3704869 Avatar asked Jun 03 '14 22:06

user3704869


2 Answers

Like this:

let interstingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13, 17],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25, 36],
]
var largest = 0
var largestKind = ""
for (kind, numbers) in interstingNumbers {
    for number in numbers {
        if number > largest {
            largest = number
            largestKind = kind
        }
    }
}
largest
largestKind
like image 135
trojanfoe Avatar answered Nov 15 '22 22:11

trojanfoe


So basically you'd want to put kind somewhere at the same time as you put number into largest, e.g. into a variable called largestKind.

like image 20
Tommy Avatar answered Nov 15 '22 23:11

Tommy