如何在SWIFT中将闭包的值设置为函数结果

问题描述 投票:-3回答:1

我被卡住了。我试图找到解决问题的好方法,但是我做不到……所以我想问你,我怎样才能把闭包的价值当作函数结果呢?我想从不同的id子项的Firebase中获取数据。因此,我的func正在工作-“ print(target!)”打印出好东西,但是如何将其作为func结果字符串呢?

    func readID(id: Int) -> String {
    var value = ""
    let ref1 = ref.child("\(av.currentYear())/\(av.currentMonth())/\(av.currentDay())/Shift\(av.shift)/\(id)").child("main").child("id")
    ref1.observeSingleEvent(of: .value) { (snapshot1) in
            if snapshot1.exists(){
                let target = snapshot1.value as? String
                print(target!)
                value = target!
            }
        }
    return value
    }

我的var值想法不起作用,并且我不想在函数外部创建10个不同的变量。我想尝试转义闭包,但我还不了解...

ios swift firebase function closures
1个回答
1
投票
func readID(id: Int, completion: @escaping ((String)->())) {
   var value = ""
   let ref1 = ref.child("\(av.currentYear())/\(av.currentMonth())/\(av.currentDay())/Shift\(av.shift)/\(id)").child("main").child("id")
   ref1.observeSingleEvent(of: .value) { (snapshot1) in
        if snapshot1.exists(){
            let target = snapshot1.value as? String
            print(target!)
            value = target!
        }
        completion(value)
    }
}

您可以通过以下方式获得返回值:

readId(30, completion: { 
    [weak self] value in
    self?.text = "This is my \(value)"
})
© www.soinside.com 2019 - 2024. All rights reserved.