swiftapioption-typeoptional-valuesuser-identification

Cannot convert return expression of type 'User' to return type 'User?' for getting currentUser from Firebase


I'm new to Swift and I'm having trouble returning a User? value from currentUser in Firebase for CURRENT_USER. I have my User class declaration below and it's located in a separate UserApi file. All the help is greatly appreciated!

var CURRENT_USER: User? {
        if let currentUser = Auth.auth().currentUser {
            return currentUser
        }
        return nil
    }

User declaration:

class User {
    var email: String?
    var profileImageUrl: String?
    var username: String?
    var id: String?
    var isFollowing: Bool?
}

extension User {
    static func transformUser(dict: [String: Any], key: String) -> User {
        let user = User()
        user.email = dict["email"] as? String
        user.profileImageUrl = dict["profileImageUrl"] as? String
        user.username = dict["username"] as? String
        user.id = key
        return user
    }
}

Solution

  • Since you have declared a User type in your project, the word User in var CURRENT_USER: User? { gets resolves to your own User type, rather than FirebaseAuth.User, which is in another module.

    To fix this, either: