Home > OS >  App crashed due to implicitly unwrapped optional (SwiftUI, Firebase)
App crashed due to implicitly unwrapped optional (SwiftUI, Firebase)

Time:07-09

I'd like to add new func to get info from my firebase about id, name, etc. from my firebase to add it in ProfileView, but the above error will occur. This is what happens when my ProfileView previews and crashes. I do not know why it happens after I wrote new function. Could you tell me how to solve it?

P.S. I apologize in advance for my bad, if I failed to state the problem correctly

func getProfile(completion: @escaping (Result<MWUser, Error>) -> ()) {
        PROBLEM IS HERE --> usersRef.document(AuthService.shared.currentUser!.uid).getDocument { docSnapshot, error in
            
            guard let snap = docSnapshot else { return }
            
            guard let data = snap.data() else { return }
            
            guard let userName = data["name"] as? String else { return }
            let id = data["id"] as? String ?? ""
            guard let phone = data["phone"] as? Int else { return }
            guard let address = data["address"] as? String else { return }
            guard let company = data["company"] as? String else { return }
            
            let user = MWUser(id: id, name: userName, phone: phone, company: company, address: address)
            
            completion(.success(user))
            
        }
        
    }

CodePudding user response:

You could try doing something like this.

if let user = AuthService.shared.currentUser {
   usersRef.document(user.uid).getDocument() { docSnapshot, error in 

//...The rest of your code. 

   }
}
else {
 // Let the user know that there is a problem
}



What this does is safely unwrap the optional value so the function only searches for a user's info in firebase if there is a current logged in user. You can then include an 'else' statement after the 'if let' to do something (like alerting the user that there is a problem) if there is not a currently logged in user. Hopefully that helps.

CodePudding user response:

The ! Operator means: Please crash my program if the optional is nil. Apparently it is, so Swift does exactly what you asked it to do and crashed. You should only use ! If you are 100% sure that the optional cannot be nil, unless there is a bug that you are going to fix.

You can do two things: Either find out why it is nil snd prevent it from ever being nil. Or handle it by writing

if let value = optional_function() {
    // Handle the case where it is not nil
} else {
    // Handle the case where it is nil
}

Or:

guard let value = optional_function() else {
    // Hsndle the case where it is nil
 }

CodePudding user response:

When you use `currentUser!`, you are force unwrapping an optional. If the optional is nil, then your program will crash.

You should unwrap it before using it. You can do that by using a guard let statement (as you did with snap and data):

guard let currentUser = AuthService.shared.currentUser else {
    // Do something where `currentUser` is nil
    return
}

usersRef.document(currentUser.uid).getDocument { docSnapshot, error in

Edit: It's not a force unwrapped option, it is an implicitly unwrapped optional.

From this SO answer:

These variables are designed so that you can defer their assignment until later in your code. It is your responsibility to ensure they have a value before you access them. However, because they involve force unwrapping, they are still inherently unsafe – as they assume your value is non-nil, even though assigning nil is valid.

One of the values on that line is an implicitly unwrapped optional, and it is nil when you are trying to access it. You should ensure that that value is initialized before you access it.

  • Related