RealmSwift and safe to force unwrap user.identity?



Is it safe to force unwrap user.identity if you have checked that the user exists?

// check that user is not nil
if let user = user {
   let config = user.configuration(realmURL: Constants.userRealm, fullSynchronization: true)
   Realm.asyncOpen(configuration: config) { (realm, error) in
       // set user name to facebook display name (using firebase auth). If that is null, force unwrap identity. 
       var userName = firebaseUser.displayName ?? user.identity!
       let user = User(id: user.identity!, username: userName, userType: User.UserType.Fan.rawValue)
       try! realm.write {

My understanding is that if the user is created successfully, it is certain there will be an identity. Is this not the case and what to do in scenarios where it is nil?


Are you asking about a Firebase user object, SyncUser, or something else? Firebase currentUser.displayName can be nil FYI and SyncUser.current.identity is an optional I believe so it could be nil.


Thanks for the response Jay. Sorry for any initial confusion. I am asking specifically about user.identity. I see in all the demos and documentation that user.identity! is force unwrapped. Is that just for brevity and in production code we should really be checking that user.identity has a value before trying to access?


If a var is optional, you should ALWAYS protect your code by safely unwrapping it and provide error handling in the case it is or at least default values. I don’t know under what situation it would be nil, but the Realm developers set it as an optional for a reason.