'How to get the sum of all Double values in a tuples array? [duplicate]

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)


Solution 1:[1]

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, +)
}

Solution 2:[2]

func getSum(myList: [(title: String, id: Int, value: Double)]) -> Double {

var key = Double()

for i in 0..<myList.count {
    key = key + myList[i].value
}

return key
}


let myList: [(String, Int, Double)] = [("A", 1, 1.5), ("B", 2, 2.5), ("C", 3, 3.5)]

print(getSum(myList:myList));   **//Output 7.5**

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vadian
Solution 2 harsh bangari