Brejuro
Brejuro

Reputation: 3541

Immutable array on a var?

I am getting the error:

Immutable value of type 'Array Character>' only has mutating members of name removeAtIndex()

The array should have contents because that removeAtIndex line is in a loop who's condition is if the count > 1

func evaluatePostFix(expression:Array<Character>) -> Character
{
    var stack:Array<Character> = []
    var count = -1 // Start at -1 to make up for 0 indexing

    if expression.count == 0 {
        return "X"
    }

    while expression.count > 1 {
        if expression.count == 1 {
            let answer = expression[0]
            return answer
        }

        var expressionTokenAsString:String = String(expression[0])
        if let number = expressionTokenAsString.toInt() {
            stack.append(expression[0])
            expression.removeAtIndex(0)
            count++
        } else { // Capture token, remove lefthand and righthand, solve, push result
            var token = expression(count + 1)
            var rightHand = stack(count)
            var leftHand = stack(count - 1)
            stack.removeAtIndex(count)
            stack.removeAtIndex(count - 1)
            stack.append(evaluateSubExpression(leftHand, rightHand, token))
        }
    }
}

Anyone have any idea as to why this is? Thanks!

Upvotes: 0

Views: 247

Answers (1)

David Berry
David Berry

Reputation: 41226

Because all function parameters are implicitly passed by value as "let", and hence are constant within the function, no matter what they were outside the function.

To modify the value within the function (which won't affect the value on return), you can explicitly use var:

func evaluatePostFix(var expression:Array<Character>) -> Character {
...
}

Upvotes: 1

Related Questions