[英]Does not conform to protocol Decodabel and Encodable
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.我试图用 String.self 替换 Var id、pushId 和 avatarLink 的空字符串,但也无济于事。
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
.当您编写
var username = String.self
, username
属性的类型将不是String
,而是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
.如果您希望
username
、 email
和status
包含字符串而不是类型,但不希望它们具有空字符串的默认值(如id
或pushId
),只需按如下方式声明它们: var username: String
。
That will enable Swift compiler to synthesize the Codable
conformance for you.这将使 Swift 编译器能够为您综合
Codable
一致性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.