S. K
S. K

Reputation: 170

fatal error: Array index out of range in swift 2

I have problem with array of GMSMarker. when i run my code its shows "fatal error: Array index out of range". I am going to remove markers from google map. i don't understand why this error comes. This is simple but pls help me to catch problem.

var MarkerList = [GMSMarker]()

    if(MarkerList.count > 0){
        for var j = 0 ; j < MarkerList.count ; j++ {
            dispatch_async(dispatch_get_main_queue()) {
                self.MarkerList[j].map = nil    
            }
        }
    }

Upvotes: 1

Views: 1899

Answers (1)

VojtaStavik
VojtaStavik

Reputation: 2472

You should run the whole for loop on the main thread. Or you can go even better and use the new forEach function in Swift2.

Before:

if(MarkerList.count > 0){
    for var j = 0 ; j < MarkerList.count ; j++ {
        dispatch_async(dispatch_get_main_queue()) {
            self.MarkerList[j].map = nil    
        }
    }
}

After:

dispatch_async(dispatch_get_main_queue()) {
    MarkerList.forEach { $0.map = nil }
}

Upvotes: 2

Related Questions