简体   繁体   English

不符合 Decodabel 和 Encodable 协议

[英]Does not conform to protocol Decodabel and Encodable

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.我试图用 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.selfusername属性的类型将不是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 .如果您希望usernameemailstatus包含字符串而不是类型,但不希望它们具有空字符串的默认值(如idpushId ),只需按如下方式声明它们: 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.

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