0
votes

Can someone tell me what's wrong with my approach? the error is

  • Type 'User' does not conform to protocol 'Decodable'
  • Type 'User' does not conform to protocol 'Encodable'

I have tried to replace the null string for Var id, pushId and avatarLink with String.self but no avail either.

Please help

struct User: Codable, Equatable{
    
    var id = ""
    var username = String.self
    var email = String.self
    var pushId = ""
    var avatarLink = ""
    var status = String.self

    static var currentId: String {
        return Auth.auth().currentUser!.uid
    }
    
    static var currentUser: User? {
        if Auth.auth().currentUser != nil {
            if let dicctionary = UserDefaults.standard.data(forKey: kCURRENTUSER) {
                
                let decoder = JSONDecoder()
                do {
                    let userObject = try decoder.decode(User.self, from: dicctionary)
                    return userObject
                } catch {
                    print("Error decoding user from user defaults ", error.localizedDescription)
                }
                
            }
        }
        
        return nil
    }
    
    static func == (lhs: User, rhs: User) -> Bool {
        lhs.id == rhs.id
    }
    
}
1
Check the documentation of Encodable and Decodable for required methods than need to be implemented.Phillip Mills
The properties id, pushId and avatarLink are all strings which themselves are codable but username, email and status are String.type (not strings) and that is not codable.Upholder Of Truth

1 Answers

6
votes

When you write var username = String.self, the type of the username property will be not String, but String.Type. Basically, it holds not a string, but a type. A type itself is not encodable or decodable, and because of that the whole struct can't be implicitly codable.

If you want username, email and status to contain strings, but not types, but don't want them to have a default value of an empty string (like id or pushId), just declare them as follows: var username: String.

That will enable Swift compiler to synthesize the Codable conformance for you.