Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Can anyone explain?

Can someone please describe, in detail, of what this code is doing. Thanks! :)

//Using tuples to make compound values
func calculateStatistics (scores: [Int]) ->
        (min: Int, max: Int, sum: Int){
    var min = scores[0]
    var max = scores[0]
    var sum = 0

    for score in scores{
        if score > max{
        max = score
        }else if score < min {
        min = score
        }
    sum += score
            }
return (min, max, sum)
}

let statistics = calculateStatistics([5, 3, 100, 3, 9])

print(statistics.sum)

print(statistics.2)

1 Answer

func calculateStatistics (scores: [Int]) ->
        (min: Int, max: Int, sum: Int){ ...

This method takes an array of integers (scores) and returns a tuple (tuples are structs, basically). The tuple contains min, max, and sum properties.

Inside the method, min, max, and sum values are calculated and we return a tuple that consists of those values.

We call this method on an array of integers and assign the resulting tuple to a constant.

We print sum property of that tuple.

We print third property (numeration starts from 0, as always) of that tuple (which happens to be sum). Under the hood, a tuple, as I said above, is a struct. But it has some additional "abilities", namely the ability to access its properties using the notation we see here in the last line of code.

To achieve similar behavior in other languages, we would have to define a struct, like that:

struct StatisticsTuple {
   let min: Int
   let max: Int
   let sum: Int
}

and have the method be rewritten like that:

func calculateStatistics (scores: [Int]) -> StatisticsTuple {
   //...
   return StatisticsTuple(min: min, max: max, sum: sum)
}

But we wouldn't be able to do this:

print(statistics.2)