2015-07-22 39 views
1

我有一個座標數組(總共965)。我想在Google Roads API中使用這些座標,但限制爲100.如何刪除所有數組項,除了在索引的倍數x - Swift

我有一個函數可以確定數組中有多少項,然後獲取要使用的值。

round(Double(userCoordinatesHardCoded.count/100)) 

產生9

我想刪除不在是的倍數指標所有項目,在這種情況下,9所以理論上我只會永遠有不超過100個項目在數組中。

如果可能,我想保留第一個和最後一個數組項。

+1

你爲什麼不與第一指標的新數組,索引%9 == 0的每個索引和最後一個索引? –

回答

0

如果空間不是問題,您可以使用所需的倍數創建另一個數組。

var oldCoordinates // Imagine it having all those elements 
var newCoordinates : GoogleCoordinates = [] // This one will have new ones 

newCoordinates.append(oldCoordinates[0]) 
var x = 1 
for (x; x < oldCoordinates.count ; x++) { 
    if (x % 5 == 0) { 
     newCoordinates.append(oldCoordinates[x]) 
    } 
} 
if (x != (oldCoordinates.count - 1)) { 
    newCoordinates.append(oldCoordinates[oldCoordinates.count - 1]) 
} 
+0

這太好了。謝謝。 – puks1978

0

我知道這已經回答了,但是這是一個偉大的使用情況下使用filter功能內置到斯威夫特:

let newCoordinates = oldCoordinates.filter { coord in 
    return (coord % 9 != 0) 
}