我试图在函数外获取Array的值,但是一旦快照的块结束,newArray的值就会为空。
即使关闭结束后,我也想访问Array的值。
将值从准备隔离传递到下一个View Controller后,该值仍为空。

var newArray = [Any]()
func getData(refe: String) -> [Any]{

    let currUser = Auth.auth().currentUser?.uid
    let ref = Database.database().reference(fromURL: "MyURL").child("users/\(currUser!)/Questions/")
    ref.child("\(refe)").observeSingleEvent(of: .childAdded, with:{ snapshot in

        let enumerator = snapshot.children
        while let rest = enumerator.nextObject() as? DataSnapshot, let value = rest.value{
            self.newArray.append(value as! Any)
        }
        print(self.newArray)
//This gives [test,test1,test2]

    })
    return newArray
// Here the Array is empty.
}


实际结果: []

预期结果:[测试,测试1,测试2]

我也试过了。

    func getData(refe: String, completion: @escaping (([Any]) -> ())) {
    var newArray = [Any]()
        let currUser = Auth.auth().currentUser?.uid
        let ref = Database.database().reference(fromURL: "MYURL").child("users/\(currUser!)/Questions/")
        ref.child("\(refe)").observeSingleEvent(of: .childAdded, with: { snapshot in

            let enumerator = snapshot.children
            while let rest = enumerator.nextObject() as? DataSnapshot, let value = rest.value{

                newArray.append(value)
            }

        completion(newArray)
    })
    }


并在辅助函数中调用它

func getDataD() -> [Any]{
    let ref = getReference()
    var arr = [Any]()
    self.getData(refe: ref) { (array) in
        arr = array
// This gives [test,test1,test2]
    }
    return arr
// This gives []
}


在那之后调用函数为segue做准备

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    guard let detailViewController = segue.destination as? HostOptionTableViewController
        else {
            return
    }
    detailViewController.ref = getReference()
    self.getData(refe: detailViewController.ref) { (array) in
        detailViewController.data = array
    }
}
}


执行后detailViewController.data的实际结果应为[test,test1,test2]
但它是 []

最佳答案

getData中调用prepareForSegue为时已晚,这应该位于导航到第二个vc的动作中

 self.getData(refe:yourRef) { array in
     self.performSegue(withIdentifier:"segueName",sender:array)
 }


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    guard let detailViewController = segue.destination as? HostOptionTableViewController
        else {
            return
    }
    detailViewController.ref = getReference()
    detailViewController.data = sender as! [Model] // Model is type of array
}


该请求是异步的,导航将在获取数据之前进行

关于swift - 如何从快照关闭中返回数组的值,并将其用于准备隔离?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57304557/

10-16 03:35