我正在创建一个移动应用程序,它以字符串的形式从 Firebase 数据库获取数据
let userID = Auth.auth().currentUser?.uid
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
// Get username
let value1 = snapshot.value as? NSDictionary
let username1 = value1?["username"] as? String ?? ""
let balance1 = value1?["balance"] as? String ?? ""
我必须使用余额创建一些计算,因此我将余额转换为整数
// Calculate the new balance
guard let bal = Int(balance1) else {
print("error")
return
}
let amt = self.amtString
let intamt = Int(amt)
//fix math
let newBalance1 = bal - intamt!
最后,计算完成后,我必须将数据传回firebase数据库
self.ref.child("users").child(userID!).setValue(["username": username1, "balance": newBalance1])
这工作正常,但问题是,它作为整数进入数据库并删除引号。我已经尝试过
let newBalance1 = "\(bal - intamt!)"
但由于某种原因,这改变了计算并给出了完全不同的值。请我需要帮助将整数转换为字符串而不改变计算。
最佳答案
解决这个问题的方法可能是问题所在。如果您需要该数字作为 int,请将其存储为 int。
这行代码...
self.ref.child("users").child(userID!).setValue(["username": username1, "balance": newBalance1])
...不“删除引号”。 newBalance1 在代码中被定义为一个整数(没有引号开头),并且这一行将整数...写入为整数。
如果您想将其转换为字符串并将该字符串写入 Firebase,此代码即可实现。
self.ref.child("users").child(userID!)
.setValue(["username": username1, "balance": String(newBalance1)])
我运行了这两行,结果是
users
some_uid
balance: 123 //this is an Int from your code
username: "some username"
和
users
some_uid
balance: "123" //this is a string from my code
username: "some username"
问题中不清楚为什么需要字符串 - 一般来说,如果您使用整数,请将它们保留为整数,例如,它可以使排序正常工作
对一系列字符串“1”、“2”、“3”、“10”进行排序将得到
1
10
2
3
而如果它们是 Int,它们将正确排序。
关于swift - 如何使用 swift 4 将 int 变量插入到 firebase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49745361/