Can someone tell me what's wrong with my approach? the error is
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 } }
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.
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.