2017-08-24 79 views
1

我使用SWIFT 3和火力点,以建立一个应用程序从火力点的数量值作减法和更新量,我想从数据库中检索量做减法,然后更新量firebase再次。我有一个函数,你将在下面看到我的firebase数据结构。检索使用SWIFT 3

功能:

func updateBal(cred: String){ 
    //creating artist with the new given values 

    if (cred != "") { 
     let credit = ["credits": cred] 
     let newCredit = credit as! Int 
     let bal = newCredit - 1 

     //let newBalanceString: [AnyHashable: Any] = [:] 
     //let newBalanceString: [AnyHashable: Any] = [AnyHashable(bal): "/(bal)"] 

     let newBalanceString = String(format:"%.2f", bal) 
     ref.child("users").child(self.user.uid).child("creditdetails").childByAutoId().updateChildValues(newBalanceString) 

     //displaying message 
     //LabelMessage.text = "Balance Updated!" 
    } 
} 

数据结构

Data Structure

当我取消与[AnyHashable: Any]线,在这条线的应用程序崩溃:

let newCredit = credit as! Int 

但是,当我发表评论与排队,我得到一个错误就行了:

ref.child("users").child(self.user.uid).child("creditdetails").childByAutoId().updateChildValues(newBalanceString) 

错误说:

无法将类型字符串到期望的参数类型的值AnyHashable:任何]

能否请您请告诉我如何解决这个问题的正确方向?

回答

0

let newCredit = credit as! Int应该总是会给你一个错误。您无法将字典类型转换为Int类型。为了获取学分为int你可以做这样的:

if let newCredit = Int(cred) { 
    let bal = newCredit - 1 
} 

当你的cred值作为一个Int检索,没有必要%.2f 还指定类型,你可以直接创建字典像以下(与“信用”字符串作为关键,因为它总是这个值):

if let newCredit = Int(cred) { 
    let bal = newCredit - 1 

    let newBalanceString = ["credits" : bal] 
    ref.child("users").child(self.user.uid).child("creditdetails").childByAutoId().updateChildValues(newBalanceString) 
} 
+0

嗨达米安我喜欢你的建议,但仍然不扣除火力点。我似乎无法得到它的工作。是否有其他解决方法使其工作 –

+0

如果您再也没有错误,那就是一个开始。现在您在Firebase上看不到任何更新?看看你的火力规则(autorisations),检查究竟你是从你的应用程序发送。 –