Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Immutable value of type [String] only has mutating members

Hi

I'm not sure what I'm missing here - but I'm struggling with this one. I have an array and I want to append values passed to it from a text input.

I have the following code in a struct:

struct ManageItems {

    var toDoItemsArray: [String] = ["Test"]

    func getNumberOfItems() -> Int {
        return toDoItemsArray.count
    }

    func addNewItem(String) {
        var newItemString = "Test"
        toDoItemsArray.append(newItemString)  }

}

My error is on the following "toDoItemsArray.append(newItemString)" // Immutable value of type '[String]' only has mutating members named 'append'

Any clues as to where I'm going wrong?

1 Answer

Hi Craig,

By default structs are immutable meaning they can't be altered or mutated as it's known, you can fix it very easily by adding the keyword mutating before func which tells the compiler that your structure needs to be altered, you should end up with the below.

struct ManageItems {
    var toDoItemsArray: [String] = ["Test"]

    func getNumberOfItems() -> Int {
        return toDoItemsArray.count
    }

    mutating func addNewItem() {
        var newItemString = "Test"
        toDoItemsArray.append(newItemString)
    }
}

EDIT: I also just realised you had a random String type set in the parameters which didn't need to be there.

Thank you, I really appreciate the help! - I didn't know that, but it makes sense. One thing I'm seeing now though is that when trying to pass something from my view controller to my model, I'm seeing the same error there now...

So I have the following in my model:

struct ManageItems {

    var toDoItemsArray = ["Buy Milk","Fix Cupboard","Write Blog"]

    func getNumberOfItems() -> Int {
        return toDoItemsArray.count
    }

    mutating func addNewItem(itemToAdd: String) {
       toDoItemsArray.append(itemToAdd)
    }

}

and in the View Controller I have the following which gives me the error:

let manageItems = ManageItems()
...
manageItems.addNewItem(itemToAdd)
// Error reads: Immutable value of type 'ManageItems' only has mutating members named 'addNewItem'  

Ah never-mind - I've worked it out:

I changed the line to read:

var manageItems = ManageItems()

This sorted out the problem.