Home > OS >  swift using map to convert from array to dictionary
swift using map to convert from array to dictionary

Time:09-28

@Published private var rates = Dictionary<String, Double>()

This works

for e in res.rates {
 self.rates[e.currencySymbol] = e.rate
}

This is returning 0 elements

let _ = res.rates.reduce(into: self.rates){ $0[$1.currencySymbol] = $1.rate }

What am I doing wrong?

CodePudding user response:

You are getting an empty dictionary because you haven't used the result of reduce(into:_:), you need to use the result of it and set it to your rates dictionary.

self.rates = res.rates.reduce(into: self.rates) { $0[$1.currencySymbol] = $1.rate }

You are thinking that when you pass self.rates reduce will use it to fill the result but it is just the initial result, so you can even set empty dictionary [:].

self.rates = res.rates.reduce(into: [:]) { $0[$1.currencySymbol] = $1.rate }
  • Related