【问题标题】:How do I edit a global variable within a closure in Swift? [duplicate]如何在 Swift 的闭包中编辑全局变量? [复制]
【发布时间】:2020-06-30 18:06:07
【问题描述】:

我正在使用 Xcode 和 Swift 编程语言开发一个应用程序。请记住,我的应用与 Firebase 密切合作。我创建了一个函数来根据键从 Firebase 检索参数。

// My global variables. 'ref' is my firebase database and 'returnValue' is the value I am trying to write to withing the closure.
var ref = Database.database().reference(withPath: "accounts")
var returnValue: String = ""


func getParam(key: String) -> String {
    let index = defs.integer(forKey: "index")

    self.returnValue = "Failed retrieving parameter in getParam() function"

    self.ref.child("data").observeSingleEvent(of: .value) { (snapshot) in

        let data = snapshot.value! as! NSArray
        let dictionary = data[index] as! NSDictionary
        self.returnValue = String(describing: dictionary[key])
        print("returnValue:", self.returnValue) //First line in console
        return
    }
    return self.returnValue
}
override func viewDidLoad() {
    super.viewDidLoad()
    print(getParam("status")) //Second line in console
}

每当我调用此函数时,我都会在控制台中看到:

returnValue: Optional(0) //记住这是我在第二行中寻找的输出

在 getParam() 函数中检索参数失败

【问题讨论】:

标签: ios swift firebase firebase-realtime-database closures


【解决方案1】:

当您调用 observeSingleElement 时,它会同步运行,这意味着当前线程将其发送出去并忽略它所做的一切。

return self.returnValue

并且与observeSingleElement 中的闭包无关。您可以将闭包传递给

func getParam(key: String, completion: (String) -> Void) {
    let data = snapshot.value! as! NSArray
    let dictionary = data[index] as! NSDictionary
    let returnValue = String(describing: dictionary[key]) ?? "Failed retrieving parameter in getParam() function"
    completion(returnValue)
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多