-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)")
}
1
  • "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 ... Commented Apr 28, 2015 at 12:44

2 Answers 2

2

This should let you going:

let x = (dictionary["gross_price_total"] as NSString).doubleValue
Sign up to request clarification or add additional context in comments.

Comments

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"])

1 Comment

Upvote for a creative way of using the exentions

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.