2020年12月19日星期六

Error When Converting JSON String To Number Using Swift

I have a basic question to convert string to number in Swift. I found a good stack overflow question that helps me convert a JSON string to a number, but I get an error when I try to add or subtract the values.

I am sure I am missing something obvious!

Phil

Error: Referencing operator function '-' on 'BinaryInteger' requires that 'NSNumber' conform to 'BinaryInteger'

func red2G()->String {          let numberFormatter = NumberFormatter()                    // Prev Close          let number1  = numberFormatter.number(from: pricesAlpha?.globalQuote.prevClose ?? "0.000")          if let final1 = number1?.floatValue {          print("Returned number is " + String(format: "%.2f", final1))          }                    // Open          let number2  = numberFormatter.number(from: pricesAlpha?.globalQuote.open ?? "0.000")          if let final2 = number2?.floatValue {          print("Returned number is " + String(format: "%.2f", final2))          }                    // Price          let number3  = numberFormatter.number(from: pricesAlpha?.globalQuote.price ?? "0.000")          if let final3 = number3?.floatValue {          print("Returned number is " + String(format: "%.2f", final3))          }                    return String(number3-number2)       }  

The values are based on this JSON Dictionary

struct GlobalQuote: Codable {      let globalQuote: PriceAlpha            enum CodingKeys : String, CodingKey {          case globalQuote = "Global Quote"      }  }    struct PriceAlpha: Codable {      let symbol: String      let open: String      let high: String      let low: String      let price: String      let volume: String      let tradingDay: String      let prevClose: String      let change: String      let pctChange: String            enum CodingKeys : String, CodingKey {          case symbol = "01. symbol"          case open = "02. open"          case high = "03. high"          case low = "04. low"          case price = "05. price"          case volume = "06. volume"          case tradingDay = "07. latest trading day"          case prevClose = "08. previous close"          case change = "09. change"          case pctChange = "10. change percent"      }  }    


from Recent Questions - Stack Overflow https://stackoverflow.com/questions/65375737/error-when-converting-json-string-to-number-using-swift TraderPhilDE http://ifttt.com/images/no_image_card.png

没有评论:

发表评论