1

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 :)

4
  • 2
    Can you add the code? The playground one works for me too, so obviously you are doing something different in your non-playground version. The error comes from trying to alter an immutable array, which can't be changed. If you add the code where you define the array, etc. then we can help you further. Commented Nov 12, 2014 at 2:04
  • @jonogilmour Here is a link to a Dropbox download: dropbox.com/s/p1oe62ehe5xvb0w/DigitArray.rtf?dl=0 Sorry it isn't a .swift file, Dropbox wouldn't let me upload it that way. I know that my programming is crude, I am a beginner and I am trying to make a class that allows me to have numbers of length longer than supported by swift. Commented Nov 12, 2014 at 2:19
  • Taking a look, I don't quite know what you are trying to do with for var x = start; arr[x] == 0; x--. This looks very messy to me. What exactly do you want to do in removeExtraZeros()? Commented Nov 12, 2014 at 2:24
  • I am attempting to remove zeros that are unnecessary in the number. For example, the first and last zeros in 051.70. That for loop is to remove the unnecessary zeros in the beginning of a number and the while loop after is to remove them at the end. Commented Nov 12, 2014 at 2:30

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

If you want help with that while loop, consider asking another question separately from this one.
Thank you. I know that it is looping as it is now, but I am going to add in arr.removeAtIndex(0). I just forgot to do so before I posted the code.
1

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:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.