Luke Patterson Luke Patterson - 3 years ago 289
Swift Question

Firebase retrieves my Double as a String in Swift iOS?

So I'm saving a dictionary to my firebase. The dictionary is located in a custom class I made called FoodItem. Here's the lines where I save the dictionary:

let favRef = self.ref.childByAppendingPath("urlhidden")

foodItem is a FoodItem object, here's the part of my FoodItem class that implements .toAnyObject()

var key: String
var ref: Firebase?
var name: String
var description: String
var minCal: Int
var maxCal: Int
var containsNuts: Bool
var vegetarian: Bool
var price: Double //**NOTE THAT PRICE IS A DOUBLE**

func toAnyObject()->[String:AnyObject]{
return ["name",

So those bits of code combined saves my data to my firebase. Works as it should. But when I retrieve the data, my price variable is a string? I'll explain...

Here's where I retrieve the data:

func getCurrentOrder(){
let uid = ref.authData.uid
ref = Firebase(url: "urlhidden")
ref.observeEventType(.Value, withBlock: { snapshot in

var newItems = [FoodItem]()

for item in snapshot.children {

let foodItem = FoodItem(snapshot: item as! FDataSnapshot)

self.order = newItems

That FoodItem constructor you see with the snapshot takes the data from my firebase and assigns my FoodItem variables to those values in my firebase. Here's that code:

init(snapshot: FDataSnapshot) {
key = snapshot.key
name = snapshot.value["name"] as! String
price = snapshot.value["price"] as! Double //**NOTE STILL A DOUBLE**
description = snapshot.value["description"] as! String
minCal = snapshot.value["minCal"] as! Int
maxCal = snapshot.value["maxCal"] as! Int
containsNuts = snapshot.value["containsNuts"] as! Bool
vegetarian = snapshot.value["vegetarian"] as! Bool

ref = snapshot.ref

However when I run my code, I see that it prints the double as a String
There are quotes around the value of my price

As you can see, there are clearly quotes around the Double variable "price".
And I get this error:

Could not cast value of type '__NSCFString' (0xff0ee0) to 'NSNumber' (0x13ff81c).

With this line of code highlighted in red:

price = snapshot.value["price"] as! Double

Which is located inside the FoodItem constructor with the snapshot as I posted above.

Any Ideas???

*EDIT: It does the same thing for my int variables. Same error message

Answer Source

It never actually saved it as a String. I believe I had that value in there as some old code in which I did save it as a String. I deleted my entries in the database and tried it again and it works just fine. Thank you to those who attempted to answer my question.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download