Reputation: 1132
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)
Upvotes: 0
Views: 247
Reputation: 1
a tuple in swift as a comma-separated list of types enclosed in parentheses and is commonly used t return multiple values. we can get results in return with dot notation. it is known as the mashup of the javascript object and arrays, for example, foo= (0, int, bool). the function is run and on the sum, it will always run and add up the values and max-min values not showing because the only sum is getting. min is 3 and max is 100. on index 2 we get 100. and sum will be 108
Upvotes: -1
Reputation: 19821
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.
Upvotes: 2