Reputation: 99
So, while learning swift, I've run into an issue with adding values to an array property. When I try to print the first value of the array after adding a value to it, I receive an index out of bounds error. How do I add a value to an array property that is accessible to the entire class?
class HomeViewController: UIViewController {
var geofences = [Geofence]()
override func viewDidLoad() {
super.viewDidLoad()
getFences()
print(self.geofences[0])
}
func getFences() {
var query = PFQuery(className:"Geofence")
query.whereKey("username", equalTo: "Peter")
query.findObjectsInBackgroundWithBlock {
(fences: [PFObject]?, error: NSError?) -> Void in
if error == nil && fences != nil {
if let fences = fences {
for (index, element) in fences.enumerate() {
var unique_id = element.objectId
var fence_radius = element["radius"] as! Int
var fence_name = element["name"] as! String
var lat = element["centerPoint"].latitude
var lon = element["centerPoint"].longitude
var center = CLLocationCoordinate2D(latitude: lat, longitude: lon)
var new_fence: Geofence? = Geofence(uniqueID: unique_id!, radius: fence_radius, centerPoint: center, name: fence_name)
self.geofences.append(new_fence!)
}
}
} else {
print(error)
}
}
}
EDIT: It seems I oversimplified the issue. Here is the code that's getting the index out of bounds error. When I retrieve the geofence from Parse, the geofences array is populated, but once it exits the getFences method, the array is emptied.
Upvotes: 2
Views: 127
Reputation: 88
It's likely that your print call is being run before getFences()
has had time to populate the array. You can check this with another print call outside of query.findObjectsInBackgroundWithBlock
Upvotes: 3