FortuneFaded
FortuneFaded

Reputation: 1329

Firebase: Saving and Retrieving Floats (Swift)

I'm trying to save and retrieve a float datatype into Firebase. I am able to save just fine and have it structured like below.

Firebase Screenshot

However, when I attempt to retrieve the value using the code

for child in snapshot.children.allObjects as! [FDataSnapshot] {

            let rating = child.value["rating"] as? Float
            print(rating)

I'm getting the following:

Optional(8.19999981)

Optional(8.69999981)

Optional(9.19999981)

What is the best way to prevent this from occurring?

Upvotes: 0

Views: 3490

Answers (1)

Jay
Jay

Reputation: 35659

Firebase doesn't directly support the float type. Numeric representations are support by NSNumber, so in general either save your number as a string or wrap it into an NSNumber when saving and reverse that when reading back in.

let p = 3.14159265
let n = NSNumber(float: Float(p))

print(n)

There are lots of alternatives as well.

Upvotes: 7

Related Questions