Reputation: 61
This is my function and I am trying to get the sum of all the Double values. I tried using += but I got many errors, I would really appreciate any assistance!
func getSum(myList: [(title: String, id: Int, value: Double)]) -> Double {
var key = Double()
for i in 0..<myList.count {
//something over here needs to change
key = myList[i].value
}
return key
}
let myList: [(String, Int, Double)] = [("A", 1, 1.5), ("B", 2, 2.5), ("C", 3, 3.5)] // should return 7.5 (1.5 + 2.5 + 3.5)
Upvotes: -1
Views: 459
Reputation: 495
//Python Version 3.8
from typing import List, Tuple
def get_sum(my_list: List[Tuple[str, int, float]]) -> float:
total = 0.0
for _, _, value in my_list:
total += value
return total
my_list = [("A", 1, 1.5), ("B", 2, 2.5), ("C", 3, 3.5)]
result = get_sum(my_list)
print(result) //Output Result 7.5
Online Python Tool: https://www.online-python.com
Upvotes: -2
Reputation: 285160
Map
the tuple to its value
value and sum it up with reduce
.
func getSum(myList: [(title: String, id: Int, value: Double)]) -> Double {
return myList.map(\.value).reduce(0.0, +)
}
Upvotes: 4