Home > database >  How to add value from object in dictionary in Swift?
How to add value from object in dictionary in Swift?

Time:03-04

I have dictionary which is having objects as value, I want to retrieve value from object.

code :

 public class Student {

    public let name: String
    public let age: Double

     public init(name: String, age: Double) {
         self.name = name
         self.age = age
     }
} 

and dictionary as ["1": Student, "2" : Student ]

How can i add all the ages of student? for 13 12.

CodePudding user response:

Here are potential solutions:

let dict = ["1": Student(name: "A", age: 13), "2" : Student(name: "B", age: 12)]

Side note, there is nothing wrong in doing a manual for loop. It's basic algorithm skills, and it's need to understand higher level methods.

Basic for loop:

var sumOfAges: Double = 0
for (_, value) in dict {
    sumOfAges  = value.age
}
print(sumOfAges)

Basic forEach loop

var sumOfAges2: Double = 0
dict.forEach {
    sumOfAges2  = $0.value.age
}

With reduce(into:_:):

let sumOfAges3: Double = dict.reduce(into: 0) { partialResult, aKeyValue in
    partialResult  = aKeyValue.value.age
}

With reduce(into:_:), and using Shorthand Argument Names (which make sense only if you understand the previous step):

let sumOfAges4 = dict.reduce(into: 0, { $0  = $1.value.age })

Additional possible step, is to transform your dictionary into a simpler data, like an array of Double.

let allAges = dict.mapValues { $0.age }
// or let allAges = dict.values.map { $0.age }
// or let allAges = dict.values.map { \.age }
// ...

You have an array of Double, then, use either a for loop, forEach, reduce(into:_) again on this "simplified array"
The downside, is that you iterate twice, one for the mapping, one for your calculation.

  • Related