This is because when you retrieve data from Firebase, the call is asynchronous. What can you do:
Option 1 - Set the logic in the closure (like what you have, type var inside the closure).
2 - , , :
func myMethod(success:([String])->Void){
ref?.observeEventType(.Value, withBlock: { snapshot in
var newNames: [String] = []
for item in snapshot.children {
if let item = item as? FIRDataSnapshot {
let postDict = item.value as! [String: String]
newNames.append(postDict["name"]!)
}
}
success(newNames)
})
}
3 -
protocol MyDelegate{
func didFetchData(data:[String])
}
class MyController : UIViewController, MyDelegate{
func myMethod(success:([String])->Void){
ref?.observeEventType(.Value, withBlock: { snapshot in
var newNames: [String] = []
for item in snapshot.children {
if let item = item as? FIRDataSnapshot {
let postDict = item.value as! [String: String]
newNames.append(postDict["name"]!)
}
}
self.didFetchData(newNames)
})
}
func didFetchData(data:[String]){
}
}