简体   繁体   中英

Type '' does not conform to protocol 'Decodable'/'Encodable'

I have this code to get information from 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

Type 'Spty' does not conform to protocol 'Decodable'

Type 'Spty' does not conform to protocol '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." 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,

  2. Dictionary, Optional are Codable if they contain Codable types

Since NSNumber is not part of Codable types, you cannot able to use it. 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

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

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.

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