[英]Error When Converting JSON String To Number Using Swift
我有一個基本問題是將 Swift 中的字符串轉換為數字。 我發現了一個很好的堆棧溢出問題,可以幫助我將 JSON 字符串轉換為數字,但是當我嘗試添加或減去這些值時出現錯誤。
我確定我遺漏了一些明顯的東西!
菲爾
錯誤:在“BinaryInteger”上引用運算符 function“-”要求“NSNumber”符合“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)
}
我根據建議的答案簡化了 function:
func load(symbolName:String) {
self.symbolName = symbolName
}
func red2G()->String {
let numberFormatter = NumberFormatter()
// Prev Close
let prevClose = numberFormatter.number(from: pricesAlpha?.globalQuote.prevClose ?? "0.000")?.floatValue
// Open
let openPrice = numberFormatter.number(from: pricesAlpha?.globalQuote.open ?? "0.000")?.floatValue
// Price
let currentPrice = numberFormatter.number(from: pricesAlpha?.globalQuote.price ?? "0.000")?.floatValue
return String((openPrice ?? 0.00) - (prevClose ?? 0.00) - (currentPrice ?? 0.00))
}
這些值基於此 JSON 字典
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"
}
}
NSNumber
是圍繞實際 integer 或浮點數或其他任何東西的 object 包裝器。 您在代碼中看到您調用floatValue
的位置嗎? 這得到了一個實際的數字,你可以用它來做數學。 將final3
和final2
放在他們的if
語句之外並對其進行數學計算。
也就是說,您幾乎肯定應該在PriceAlpha
中實現自定義解碼和編碼,以便結構已經包含正確語義類型(例如Float
)而不是String
的值。 但是對於財務信息,您實際上需要Decimal
,而不是Float
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.