liam923
liam923

Reputation: 1021

Swift: Can't remove item from array using removeAtIndex

I have an array named arr of type [Int8]:

var arr: [Int8] = []

Throughout the program I add items to the array using append and insert. However, when I try to remove an item using arr.removeIndexAt(x), it throws the error:

Playground execution failed: <EXPR>:144:13: error: immutable value of type '[Int8]'
only has mutating members named 'removeAtIndex'
        arr.removeAtIndex(x)

Why is this happening? I tried recreating this in a playground:

var arr: [Int8] = []
arr.append(1)
arr.removeAtIndex(0)

and it works fine. Could someone please explain to me how I might fix this problem or remove an item another way? Any help wold be great. Thanks :)

Upvotes: 1

Views: 509

Answers (2)

linimin
linimin

Reputation: 6377

You say when you try to remove an item using arr.removeIndexAt(x), it throws the error.

Because the method name is removeAtIndex:, not removeIndexAt:

Upvotes: 1

jonogilmour
jonogilmour

Reputation: 673

Found the solution. Add mutating to your definition of removeExtraZeros() to allow it to alter properties, i.e,

mutating func removeExtraZeros() { ... }

Unfortunately you run into an issue where the while loop after that for loop is looping infinitely, so consider revising that part as well.

Upvotes: 1

Related Questions