WasimSafdar - 1 year ago 55

Swift Question

I just started learning swift from "The Swift Programming Language(Swift 3 beta)". I came across a function that has tuple return type. They have not fully explained it. Here func "calculateStatistics" takes in "score" array of Int type and it has tuple compound as a return type. Now in the end when they call it with print statement, I do not understand, what is meant by "print (statistics.2)" statement. What ".2" means and how it is calculated.

`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)

Answer

A tuple is similar to a simple struct, in that example you have a "struct" with 3 elements and with `statistics.2`

they are referring to the 3rd element of the tuple, sum (index starting from 0).

Since that function also defines a name for the individual elements, `statistic.sum`

works too.

Source (Stackoverflow)