访问函数外部的变量 - swift

时间:2017-02-01 09:23:13

标签: 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

}

2 个答案:

答案 0 :(得分:1)

您正在执行异步操作,因此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"] } } } 完成之前返回。你可以看看这样的......

{{1}}

答案 1 :(得分:1)

如评论中所述,无法从包含异步任务的方法返回某些内容

您需要一个完成块,例如

?embed=true
http://kibana/app/kibana#/visualize/edit/chart?embed=true&_g=(refreshInterval:(display:Off,pause:!f,value:0),...