简体   繁体   中英

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
    }
}

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

To fix this, either:

  • rename your own User to something such as UserInfo , or;

  • Add the prefix FirebaseAuth. to User to differentiate:

     var currentUser: FirebaseAuth.User? { Auth.auth().currentUser }

    You can also add a typealias to give the Firebase User a different name:

     typealias FirebaseUser = FirebaseAuth.User

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM