致命错误:数组索引超出swift 2的范围

时间:2021-01-02 16:38:50

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.

我有GMSMarker数组的问题。当我运行我的代码时,它显示“致命错误:数组索引超出范围”。我要从谷歌地图中删除标记。我不明白为什么会出现这个错误。这很简单,但请帮助我解决问题。

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    
            }
        }
    }

1 个解决方案

#1


0  

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.

你应该在主线程上运行整个for循环。或者你可以更好地使用Swift2中的新forEach函数。

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 }
}

#1


0  

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.

你应该在主线程上运行整个for循环。或者你可以更好地使用Swift2中的新forEach函数。

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 }
}