If you’re using Firebase with your iOS App, you’re most likely going to map your values back to struct or a class.

1
2
3
4
5
6
https://myFirebaseUrl.com/users 
/-3948kU-0fm/
{
username: "mbalex99",
age: 24
}

And your model in Swift might look like this:

1
2
3
4
5
6
struct UserModel {
var username: String
var displayName: String?
var age: Int
var points: Int?
}

Mapping them seems pretty easy but since iOS doesn’t give us robust reflection, we’ll have to do it manually. If you’re app starts getting larger, this is a big place to make errors. FDataSnapshot’s value object is of type AnyObject. That means to get the keys to map back to your model need to be casted or unwrapped safely into the struct. You certainly don’t want to do this:

1
2
let value = snapshot.value
let username: String = value["username"] as! String

And this can get really out of control quickly (especially when you have a lot properties):

1
2
3
4
5
6
let value = snapshot.value
if let safeUsername = value["username"] as? String {
username = username
}else{
username = ""
}

Here’s where SwiftyJSON can help tremendously.

You can install it easily using cocoapods:

1
pod 'SwiftyJSON'

Here’s some sample code.

1
2
3
4
5
import SwiftyJSON

let json = JSON(snapshot.value)
username: String = json["username"].stringValue // .stringValue gives you back the string, if somethings off it'll just be ""
displayName = json["username"].string // .string gives you back a String?

You can follow the same pattern for int, intValue, double, doubleValue etc…
The great thing is that you don’t have to handle exceptions. The JSON type operates like a dictionary and all you have to do is read the primitive type that you’d like for each key.

Simple!

Bonus Extension Method:

Swift gives us awesome extension method and property capabilities to drastically reduce code bloating.

I suggest you add an extension method on Firebase’s FDataSnapshot class with an extension property of type JSON:

1
2
3
4
5
6
7
8
import SwiftyJSON
import Firebase

extension FDataSnapshot {
var json : JSON {
return JSON(self.value)
}
}

Now you can use this read property very easily:

1
snapshot.json["username"].stringValue

Bonus Extension Method 2:

If you’re using [RxSwift]https://github.com/ReactiveX/RxSwift() you might be mapping the snapshot out very frequently in your Observables.

You can added another property called rx_json:

1
2
3
4
5
6
7
8
9
10
11
12
13
import SwiftyJSON
import Firebase
import RxSwift

extension FDataSnapshot {
var json : JSON {
return JSON(self.value)
}

var rx_json: Observable<JSON> {
return just(self.json)
}
}