Signal SIGABRT and Could not cast value of type 'NSNull'to 'NSDictionary'

I got Could not cast value of type 'NSNull'to 'NSDictionary' log and a Signal SIGABRT at the line

self.email = (snapshot.value! as! NSDictionary)["email"] as? String

when I click the create account button and redirect me to a new page. This is the complete file

struct Users {
    var username: String!
    var email: String?
    var country: String?
    var photoURL: String!
    var biography: String?
    var uid: String!
    var ref: DatabaseReference?
    var key: String?
    var firstLastName: String!
   
    init(snapshot: DataSnapshot){
       
        key = snapshot.key
        ref = snapshot.ref
       
        /
        self.email = (snapshot.value! as! NSDictionary)["email"] as? String
        self.username = (snapshot.value! as! NSDictionary)["username"] as! String
        self.country = (snapshot.value! as! NSDictionary)["country"] as? String
        self.uid = (snapshot.value! as! NSDictionary)["uid"] as! String
        self.biography = (snapshot.value! as! NSDictionary)["biography"] as? String
        self.photoURL = (snapshot.value! as! NSDictionary)["photoURL"] as! String
        self.firstLastName = (snapshot.value! as! NSDictionary)["firstLastName"] as! String
       
    }
   
  

Your first problem is too many exclamation marks. Every time you use '!' you're telling Swift that you can guarantee variables and types are exactly what you say they are. If it detects while running that you've lied, it crashes.


The fix is to test values rather than insisting they are something that they obviously are not.


As a start, try debugging the value of "snapshot" in your init to see what it really contains.

Signal SIGABRT and Could not cast value of type 'NSNull'to 'NSDictionary'
 
 
Q