Search code examples
swiftuiintegerdoublensnumber

Errors after changing NSNumber to Int/Double


I have this class to get data from Firestore:

 struct Spty: Identifiable{
  var id: String
  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
            }
        }
    }
}

 }

And I Displayed it using ForEach:

     ForEach(sptyModel.specialities){ spty in
         NavigationLink(destination: More()) {
                       HStack{
                                
                         Text(spty.spty).foregroundColor(.yellow)
                           .frame(width: UIScreen.main.bounds.width - 30)
                           .frame(height: 105)
                           .background(Color(UIColor(red: CGFloat(truncating: spty.r) / 255.0, green: CGFloat(truncating: spty.g) / 255.0, blue: CGFloat(truncating: spty.b) / 255.0, alpha: 1.0)))
                           .cornerRadius(38)
                           .padding(.bottom, 20)
                            }       
                    }
                }

Because of the necessity of the usage of Codable, I need to change NSNumber to Int/Double. After simply just changing it in the class SptyViewModel, I got the following errors in ForEach

image

How can I solve them


Solution

  • Your problem is not with the ForEach , but the .background(...)

    CGFloat(truncating:NSNumber) accept NSNumber only .

    ForEach(sptyModel.specialities){ spty in
                    NavigationLink(destination: Text("MORE")) {
                        HStack{
                            Text(spty.spty).foregroundColor(.yellow)
                                .frame(width: UIScreen.main.bounds.width - 30)
                                .frame(height: 105)
                                .background(Color(UIColor(red: CGFloat(truncating: NSNumber(value: spty.r)) / 255.0, green: CGFloat(truncating: NSNumber(value: spty.g)) / 255.0, blue: CGFloat(truncating: NSNumber(value: spty.b)) / 255.0, alpha: 1.0)))
                                .cornerRadius(38)
                                .padding(.bottom, 20)
                        }
                    }
                }