访问函数外部的变量 - swift



我正在尝试访问函数外部的变量,我尝试在类外部声明变量,但它一直在声明中显示初始值而不是函数内部的值,这是我的代码,我需要访问 databaseScore

func getDatabaseScore()-> Int{
    let ref2 = FIRDatabase.database().reference().child("users").child("user").child((user?.uid)!)
    ref2.observeSingleEvent(of: .childAdded, with: { (snapshot) in
        if var userDict = snapshot.value as? [String:Int] {
            //Do not cast print it directly may be score is Int not string
            var databaseScore = userDict["score"]
        }

    })
    return databaseScore
}

如注释中所述,不可能从包含异步任务的方法返回某些内容

例如,您需要一个完成块

func getDatabaseScore(completion: (Int?)->()) {
    let ref2 = FIRDatabase.database().reference().child("users").child("user").child((user?.uid)!)
    ref2.observeSingleEvent(of: .childAdded, with: { (snapshot) in
        if let userDict = snapshot.value as? [String:Int] {
            //Do not cast print it directly may be score is Int not string
            completion(userDict["score"])
        }
        completion(nil)
    })
}

getDatabaseScore() { score in 
   guard let score = score else { return }
   // do something with unwrapped "score"
}

您正在执行异步操作,因此getDatabaseScore observeSingleEvent完成之前返回。你可以看看这样的东西...

class MyClass {
    var databaseScore: Int = 0
    func getDatabaseScore() {
        let ref2 = FIRDatabase.database().reference().child("users").child("user").child((user?.uid)!)
        ref2.observeSingleEvent(of: .childAdded, with: { (snapshot) in                 
            if let userDict = snapshot.value as? [String:Int] { 
                 print(userDict["score"]) // Confirm you have the a value
                 self.databaseScore = userDict["score"]
             }
         }
    }

最新更新