Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift error "Immutable value only has mutating members"

Tags:

macos

swift

When compiling the following Swift code (in Sample.swift):

import Cocoa

class Sample {
    func doSomething() {
        var stringArray = Array<String>()
        stringArray.append("AAA")
        addToString(stringArray)
        stringArray.append("CCC")
    }

    func addToString(myArray:Array<String>) {
        myArray.append("BBB")
    }
}

I get the following error on the line 'myArray.append("BBB")':

Immutable value of type 'Array<String>' only has mutating members named 'append'

How do I fix the code to allow a call to this mutable method?

Many thanks in advance

like image 841
gepree Avatar asked Jan 11 '23 03:01

gepree


1 Answers

If you want to modify the array you have to specify it as in an inout parameter like this func addToString(inout myArray:Array<String>). Then when you call the function you have to add & in front of your argument to show that it can be modified by the function. Your code will look something like this:

class Sample {
    func doSomething() {
        var stringArray = Array<String>()
        stringArray.append("AAA")
        addToString(&stringArray)
        stringArray.append("CCC")
    }

    func addToString(inout myArray:Array<String>) {
        myArray.append("BBB")
    }
}

You may want to take a look at in-out parameters on this page.

like image 81
Connor Avatar answered Jan 16 '23 21:01

Connor