简体   繁体   English

类型 '' 不符合协议 'Decodable'/'Encodable'

[英]Type '' does not conform to protocol 'Decodable'/'Encodable'

I have this code to get information from firestore:我有这段代码可以从 firestore 获取信息:

 struct Spty: Identifiable, Codable{
   @DocumentID var id: String? = UUID().uuidString
   var spty: String
   var r: NSNumber
   var g: NSNumber
   var b: NSNumber
}

 class SptyViewModel: NSObject, ObservableObject{
   @Published var specialities = [Spty]()
   @Published var search = ""
     func fetchData(){
      let db = Firestore.firestore()
        db.collection("specialities").addSnapshotListener { (querySnapshot, error) in
        guard let documents = querySnapshot else {return }
        self.specialities = documents.documents.compactMap { (doc) -> Spty? in
          let id = doc.documentID
            if  let spty = doc.get("spty") as? String,
            let r = doc.get("r") as?  NSNumber,
            let g = doc.get("g") as?  NSNumber,
            let b = doc.get("b") as?  NSNumber{
            
            return Spty(id: id, spty: spty, r: r , g: g , b: b )
            }
            else{
                return nil
            }
        }
      }
    }

   }

after seeing this video , I started to make the changes on my code.看到这个视频后,我开始对我的代码进行更改。 But, as I added Codable I got those errors但是,当我添加Codable ,我得到了这些错误

Type 'Spty' does not conform to protocol 'Decodable'类型“Spty”不符合协议“Decodable”

Type 'Spty' does not conform to protocol 'Encodable'类型“Spty”不符合协议“Encodable”

图片

As you can see here "The simplest way to make a type codable is to declare its properties using types that are already Codable. These types include standard library types like String, Int, and Double; and Foundation types like Date, Data, and URL. Any type whose properties are codable automatically conforms to Codable just by declaring that conformance."正如您在此处看到的“使类型可编码的最简单方法是使用已经可编码的类型声明其属性。这些类型包括标准库类型,如 String、Int 和 Double;以及基础类型,如 Date、Data 和 URL . 任何属性可编码的类型只要声明符合性就自动符合 Codable。” That means that if you want to use codable, it is necessary to use:这意味着如果要使用可编码,则必须使用:

  1. Built-in Codable types — String, Int, Double, Data, URL Array,内置可编码类型— String、Int、Double、Data、URL Array、

  2. Dictionary, Optional are Codable if they contain Codable types Dictionary, Optional如果它们包含 Codable 类型,则它们是 Codable

Since NSNumber is not part of Codable types, you cannot able to use it.由于 NSNumber 不是 Codable 类型的一部分,因此您无法使用它。 This link has a similar question to yours and you can see there the same explanation.链接与您的问题类似,您可以在那里看到相同的解释。

Instead of NSNumber use native Swift types, like Double, and align other code to that代替 NSNumber 使用本机 Swift 类型,如 Double,并将其他代码与该类型对齐

struct Spty: Identifiable, Codable{
   @DocumentID var id: String? = UUID().uuidString
   var spty: String
   var r: Double
   var g: Double
   var b: Double
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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