2

Both assignment lines in the code below give me this error:

'@|value $T5' is not identical to 'String'

   func PrintShoppingList(myList: Array<String>)
    {
        println(myList)
        var cabbage = "cabbage"
        let fish:String = "fish"
        myList[0] = cabbage
        myList[1] = fish
    }

What is wrong?

2 Answers 2

5

Parameters are constants by default and you cannot mutate them. You can change them to var, but this will be a copy of array.

func PrintShoppingList(var myList: Array<String>)
{
    println(myList)
    var cabbage = "cabbage"
    let fish:String = "fish"
    myList[0] = cabbage
    myList[1] = fish
}

You can also use inout parameter to mutate original value, but remember that array length cannot be extended by superscript, so myList[1] = fish will crash in this case.

func PrintShoppingList(inout myList: Array<String>)
{
    println(myList)
    var cabbage = "cabbage"
    let fish:String = "fish"
    myList[0] = cabbage
    myList.append(fish)
} 
Sign up to request clarification or add additional context in comments.

Comments

3

The problem here is that the argument passed to function is by default set as constant and is immutable. So you need to declared it as var to be able to mutate it.

func PrintShoppingList(var myList: Array<String>)
{
    println(myList)
    var cabbage = "cabbage"
    let fish:String = "fish"
    myList[0] = cabbage
    myList[1] = fish
    print(myList)
}

Your app might crash if you pass array with less than 2 elements, since you are accessing myList[0] and myList[1]. So, make sure that your array has at least to elements to pass array to this method.

1 Comment

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.