/ coding

Answers to the Swift experiments in the Swift Apple iBook

In Apple’s book The Swift Programming Language, the reader is presented with various “experiments” during the chapter “A Swift Tour”. These experiments are small challenges for you to try out what you are learning in a Playground.

Here’s one example of an experiment in the for in loop section:


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

And my answer:

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:String? = nil
for (kind, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largestKind = kind
            largest = number

This returns:

{Some "Square"}

These were the results I was expecting, so assuming I understood the experiment prompt correctly, the code above is an acceptable answer.

I searched around for a list of answers just to check if I’m doing these right, but I haven’t seen much yet. I did find this list of answers in a Gist by rainypixels on GitHub. If you’re stuck, this may be a good place to start.