From the comments it seems as though you have already figured out a solution, I’d like to add the following information for other’s as reference:
You should not be storing nil values in firebase (or any database for that matter as it breaks 1NF for repeating values) if a value is not required, it should only be set to the database if it exists. Otherwise initialize it as nil and use Optional Chaining to safely unwrap the value if it exists.
Consider the following object that initializes it’s non-required property ‘title’ to nil
Class CustomObject: NSObject {
//…
var title: String? = nil
//…
}
Setting
When setting the value in firebase we can use optional chaining to set the value if it exists, otherwise, do not add it to the values to be saved to the child object’s reference in firebase and remove the current value if it exists.
//Create a new reference to Firebase Database
var ref: DatabaseReference!
ref = Database.database().reference().child(<#your child id#>)
//Make a Dictionary of values to set
var values:[String:Any] = [:]
//Set required values like uuid or other primary key
//Use Optional Chaining to set the value
//Note that if title is nil
//it doesn’t override any existing value in firebase for title i.e. the old value will still remain.
if let title = myObject.title {
values["title"] = title
} else {
//if the value was previously set but now is not,
//we should update firebase by removing the value.
ref.child("title").removeValue()
}
//…
//Finally, push the remaining values to firebase to up date the child
ref.updateChildValues(values)
Getting
To get the value from firebase, we again use Optional Chaining to see if a value for the given key exists, here I am accessing the object by its child path, your query may be different but the concept is the same.
//Create a new reference to Firebase Database
var ref: DatabaseReference!
ref = Database.database().reference().child(<# child path #>)
ref.queryOrderedByValue().observeSingleEvent(of: .value) { (snapshot) in
if (snapshot.value is NSNull) {
print("No Items to Fetch")
} else {
//enumerate over the Objects
for child in snapshot.children.allObjects as! [DataSnapshot] {
if let object = child.value as? [String : AnyObject] {
let myObject = CustomObject()
if let title = object["title"] as? String {
myObject.title = title
}
//If There is no value for 'title' it will not be set.
//…
//Then use the value as you normally would…
if (myObject.title != nil) {//..}