user6283450 user6283450 - 1 year ago 114
Swift Question

Index out of range in Swift with removeAtIndex

I tried to remove an element in NSUserDefaults which is the same as stockSymbol's value when click a button. My idea is that cast the NSUserDefaults to an array and remove the element with removeAtIndex. Here is my code.

@IBAction func buttonFilledStarClicked(sender: AnyObject) {
NSLog("Filled star clicked")
self.buttonFilledStar.hidden = true
self.buttonEmptyStar.hidden = false

var Array = NSUserDefaults.standardUserDefaults().objectForKey("favorites")! as! [String]
var countArray = (NSUserDefaults.standardUserDefaults().objectForKey("favorites")! as! [String]).count - 1

for i in 0...countArray {
if stockSymbol! == Array[i] {
NSLog("i is : \(i)")
else {}

NSLog("Array is: \(Array), countArray is: \(countArray)")


However it has 'out of index' error.
It works when I just comment
Array looks like this --
["aa", "bb", "Test!", "Test!"]
Any suggestions? Thank you in advance.


You should not remove it from inside of the loop, when you call removeAtIndex(i) Array removes the item so you have 1 less item then countArray.. so you have to have another array to remember which item you want to remove and remove it outside of the loop.. or better option is to use filter

// Filter only strings that match stockSymbol
Array = Array.filter { $0 == stockSymbol! }