-2

I have a dictionary as a response from server:

{ 
  "gross_price" = "6.00";
  "gross_price_total" = "6.00";
  "guests_count" = 1;
}

Then I try:

 let x = dictionary["gross_price_total"] as? Double
 let y = dictionary["gross_price_total"]!
 println("result: \(x) \(y)")

As an output I get:

result: nil 6.00

Why? Is it not a Double?

It results that my final code doesn't work:

if let grossPriceTotal = dictionary["gross_price_total"] as? Double {
    println("final result: \(grossPriceTotal)")
}
Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
  • `"6.00"` is a string, not a number. And if you search for "Swift string to double" then you should find some answers, some are already in the "Related" section ... – Martin R Apr 28 '15 at 12:44

2 Answers2

2

This should let you going:

let x = (dictionary["gross_price_total"] as NSString).doubleValue
Miknash
  • 7,888
  • 3
  • 34
  • 46
1

You can create an extension where you can initialize your Double with a String. But you have to use the NSString-method doubleValue:

extension Double{
    init(string:String){
        self = (string as NSString).doubleValue
    }
}

let x = Double(string: dictionary["gross_price_total"])
Christian
  • 22,585
  • 9
  • 80
  • 106