0

Context - I'm currently learning Swift Struct. So I decided to create my own Phone structure in Playground. (see below)

Problem - The downloadApp method on the phone struct is throwing the following error.. Cannot use mutating member on immutable value: 'self' is immutable.

Expect outcome - To peacefully append new strings to my apps property, which is an array of strings.

Swift code

struct Phone {
    let capacity : Int
    let Brand : Sting
    var name: String
    let model: String
    var apps: [String]
    var contacts: [String]

    var formatCapacity: String {
        return "\(capacity)GB"
    }

    func downloadApp(name: String){
        apps.append(name) // ERROR 
    }
}

1 Answer 1

1

You simply need to mark downloadApp as mutating. The issue is caused by the fact that downloadApp is declared in a struct type, which is a value type and hence if you mutate any properties (namely, the apps array here) of the struct, you actually mutate the struct itself. By marking the function as mutating, the compiler allows such modification of the struct through a member function of the type.

mutating func downloadApp(name: String){
    apps.append(name)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! Apples Intro to app development book didn't show me that! Baby steps I guess

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.