【问题标题】:How to set value of closure as function result如何将闭包的值设置为函数结果
【发布时间】:2020-05-14 11:22:56
【问题描述】:

我卡住了。我试图找到解决问题的好方法,但我不能......所以我想问你,我怎样才能将闭包的价值作为 func 结果?我想从不同 id child 的 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 value 想法行不通,我不想在函数之外创建 10 个不同的变量。我想尝试转义闭包,但我还不明白...

【问题讨论】:

标签: ios swift firebase function closures


【解决方案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)"
})

【讨论】:

  • 以及如何将返回值添加到字符串?例如: var text = "This is my (readID(1, completion: { value in value}))" 所以我不想打印它,或者添加到 var,而只是读入字符串。是否可以? :)
  • 这是一个异步调用,所以像功能主义者一样正常返回在这里是行不通的。我已经为这个查询编辑了上面的答案。
猜你喜欢
  • 1970-01-01
  • 2023-04-09
  • 2017-08-05
  • 2013-04-30
  • 2019-05-31
  • 2015-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多