0

Hi all I'm creating a chat app, using firebase.

when I get to the screen to create a channel it crashes saying found nil while unwrapping optional value. If i go back into the app the channel has been created so i presume it is finding nil when changing viewcontrolers and there must be nothing in the database for the new channel under messages. below is the code and where it crashes.

var channelRef: FIRDatabaseReference?

private lazy var messageRef: FIRDatabaseReference = self.channelRef!.child("messages")

then it crashes here...

private func observeMessages() {
    messageRef = channelRef!.child("messages")

this function is called on view did load

Tony Merritt
  • 1,177
  • 11
  • 35
  • 2
    `channelRef` is `nil`. When you unwrap it (`!`), it crashes. Please read [What does fatal error unexpectedly found nil while unwrapping an optional value mean](http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu/32170457#32170457) – vadian Feb 15 '17 at 16:00

1 Answers1

0

Instead of force unwraps you should use and if let like this:

if let channelRef = channelRef {
     messageRef = channelRef.child("messages")
} //maybe add an else and do some logic if value is not there

Or you could declare var channelRef: FIRDatabaseReference! if you expect it to always be there and be of this type

anho
  • 1,705
  • 2
  • 20
  • 38
  • Cheers for your comment I tried the solution but then it moves the same error above to the first part of the code. var channelRef: FIRDatabaseReference? private lazy var messageRef: FIRDatabaseReference = self.channelRef!.child("messages") when i hover over self it shows chanel ref as nil – Tony Merritt Feb 15 '17 at 21:41
  • it is `nil` because doing `private lazy var messageRef: FIRDatabaseReference = self.channelRef!.child("messages")` doesn't work since `self.channelRef ` is `nil` at that point...you need to initialize that first and then initialize the `messageRef ` you should do just `var messageRef: FIRDatabaseReference!` – anho Feb 15 '17 at 23:15