1

I try to use Firebase framework and use it in my app, but I have a problem with undestanding, how to retrieving data from firebase and save it in my own array. Firebase structure is very simple and looks like that: enter image description here

Now my code looks like that:

`var rootRef = Firebase(url: "https://mathgamepio.firebaseio.com/")


var array:[String]?
var count: Int = 0

override func viewDidLoad() {
    super.viewDidLoad()



    rootRef.observeEventType(.ChildAdded) { (snap: FDataSnapshot!) -> Void in


        self.count++
        let math = snap.value["math"] as! String
        print(self.count)
        print(math)


        self.array?.append(math)
        print(self.array)
        print("--------")

    }`

The result of this operation looks like that:

enter image description here

self.array.append doesn't work and is nil always. How to add this data to my own array?

0

1 Answer 1

0

It looks like your array is never initialized, so self.array? will always skip append.

One solution is to check of the array exists:

if (self.array?.append(math)) == nil {
    self.array = [math]
}

There are probably more ways to solve this, but I modified the answer from this question: Adding elements to optional arrays in Swift

Update

Even easier is to simply create the array, before using it:

var array:[String]?
var count: Int = 0

override func viewDidLoad() {
    super.viewDidLoad()

    self.array = [];

    rootRef.observeEventType(.ChildAdded) { (snap: FDataSnapshot!) -> Void in


        self.count++
        let math = snap.value["math"] as! String
        print(self.count)
        print(math)

        self.array?.append(math)
        print(self.array)
        print("--------")

    }
}

Or simply not mark the array as optional:

var array:[String] = []
var count: Int = 0

override func viewDidLoad() {
    super.viewDidLoad()

    rootRef.observeEventType(.ChildAdded) { (snap: FDataSnapshot!) -> Void in

        self.count++
        let math = snap.value["math"] as! String
        print(self.count)
        print(math)

        self.array.append(math)
        print(self.array)
        print("--------")

    }
}

TIL I learned some basic Swift syntax. :-)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.