[英]Converting Firebase .value to NSDecimal - Swift
我是Swift的新开发人员。 我正在使用Swift 4.2和Xcode 10.1。
我需要从firebase中提取一个表示美元和美分的数字(例如10.20),然后将其加到该数字上,除以该数字等。结果应始终在小数点后有两个数字。
我正在尝试使用NSDecimalNumber
,但是在转换时遇到错误。
这是我的代码。 addend
的类型为NSDecimalNumber
。
dbRef.observeSingleEvent(of: .value) { (snapshot) in
// Get the balance
let NSbalance = snapshot.value as! NSDecimalNumber
// Add the addend
let balance = NSbalance + addend
// Set the new balance in the database and in the user defaults
dbRef.setValue(balance)
defaults.set(balance, forKey: Constants.LocalStorage.storedBalance)
}
我收到错误消息: Cannot convert value of type 'NSDecimalNumber' to expected argument type 'Self'
。 当我接受其建议并进行以下更改时: Replace 'NSbalance' with 'Self(rawValue: Self.RawValue(NSbalance))
” Replace 'NSbalance' with 'Self(rawValue: Self.RawValue(NSbalance))
我会得到“使用未解析的标识符Self”。
我是否应该为此使用NSDecimalNumber
? 如果没有,我该怎么办?
解决方案是将Double
用作类型。 如果值是数字(不是字符串),则Firebase Realtime数据库中的.value
类型为NSNumber
,因此我可以轻松地将其转换为Double
。 尽管Double
对于以10为基数的计算不具有Decimal
精度,但对于我使用的低级货币值,其精度要高得多,后者始终只有小数点后的两个数字。 然后,我使用数字格式化程序将其格式化为货币,并消除小数点后的多余数字。 起作用的代码如下:
该代码在服务中,用于增加金额以增加余额:
dbRef.observeSingleEvent(of: .value) { (snapshot) in
// Get the snapshot value
let NSbalance = snapshot.value as! Double
// Add the addend
let balance = NSbalance + addend
// Set the new balance in the database and in the user defaults
dbRef.setValue(balance)
defaults.set(balance, forKey: Constants.LocalStorage.storedBalance)
这段代码在显示余额的视图控制器中:
dbRef.observe(.value) { (snapshot) in
//Get the balance
self.balance = snapshot.value as! Double
// Format the balance
let currencyFormatter = NumberFormatter()
currencyFormatter.numberStyle = .currency
let balanceString = currencyFormatter.string(from: self.balance as NSNumber)
self.balanceLabel.setTitle(balanceString, for: .normal)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.