Ben
Ben

Reputation: 4867

How to cast [String:Int] to [String:Double]

I have a function that requires a dictionary in the format [String:Double], but my data is currently a [String:Int].

I'd really like to be able to convert the dictionary using a one-liner, such as

let doubles = ints as! [String:Double]

But that doesn't seem to work, giving the error message Cannot convert value of type '[String : Int]' to type '[String : Double]' in coercion

Whilst I'm sure I could work around the problem, I'd really like to understand

  1. Why I can't convert '[String : Int]' to '[String : Double]'
  2. What method I should use (perhaps something like .map would work?)

Many thanks in advance!

Upvotes: 0

Views: 293

Answers (1)

Stefan Salatic
Stefan Salatic

Reputation: 4513

Something like this might work:

for (key, value) in dictionary {
    newDictionary[key] = Double(value)
}

Upvotes: 2

Related Questions