Daibaku Daibaku - 6 months ago 5842
Swift Question

Firebase create model which has optional values in swift

I would like to create model which has optional values.
I implemented

to achieve that. node look like this and imageUrl does not exist everytime like so.

"Post": {
"uid": {
"Text": "some text",
"Date": "some date",
"imageUrl": {
autoID1: url1,
autoID2: url2
"Text": "some text",
"Date": "some date"

I created a model here

import UIKit
import Firebase

extension DataSnapshot {
var snapshots: [DataSnapshot] {
return children.allObjects.flatMap({ $0 as? DataSnapshot })
var string: String? { return value as? String }
var url: URL? { return string.flatMap({ URL(string: $0) }) }
var urls: [URL] { return snapshots.flatMap({ $0.url }) }

struct Post {

let snapshot: DataSnapshot?

var Date: String!
var imageUrl: [URL]?
var Text: String!

init(snapshot: DataSnapshot) {

self.snapshot = snapshot
self.Date = snapshot.child["Date"].string
self.imageUrl = snapshot.child["imageUrl"].urls
self.Text = snapshot.child["Text"].string

but inside
, error says

Value of type 'DataSnapshot' has no member 'child'

Does anyone know how to solve this?
Also is this right way to create function like twitter post with multiple images and sometimes images are none, only text displayed.

Answer Source

DataSnapshot doesn't have the member child, doc here. So to be able to extract something from the DataSnapshot, you might use this idea:

if let value = snapshot.value as? [String: Any] {
  self.Date = value["Date"] as? String ?? ""
  self.Text = value.child["Text"] as? String ?? ""

  // extracting the urls
  if let urls = value.child["tweetImageUrl"] as? [String:String] {
    self.imageUrl = urls.flatMap { k,v in URL(string:v) }

Note that: flatMap is awesome because provide the possibility to skip automatically all the iterations that are returning an optional value.

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