The one thing I never really understood when learning Swift was closures. I always find it quite confusing to work with them.
Could someone please explain what I have done false in the code below.
for id in myCircles{
var circleName = ""
var circleCategory = ""
var circleID = ""
ref.child("\(id)").observeSingleEvent(of: .value, with: { snapshot in
let value = snapshot.value as? NSDictionary
circleName = value?["name"] as? String ?? ""
circleCategory = value?["category"] as? String ?? ""
circleID = value?["id"] as? String ?? ""
self.defaults.setValue([circleName, circleID, circleCategory], forKey: "newestCircle"+"\(id)")
}) { error in
}
//the problem is that the part below gets executed before the closure, which is when the value should be added. The part below must be executed after the closure.
let retrievedData = self.defaults.value(forKey: "newestCircle"+"\(id)") as? [String] ?? ["","",""]
self.addCircle(circleName: retrievedData[0], circleID: retrievedData[1], circleCategory: retrievedData[2])
}
As the comment says, my .observingSingeEvent closure is called after the code beneath the closure. Not only is it called after the code below the closure, but it is called after the entire for-loop, as many times as it would have been called, had it been called inside of the loop. I don't understand why this is, can someone please help me?