Samuel
Samuel

Reputation: 6136

Unable to append string to mutable array in Swift

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 
    }
}

Upvotes: 0

Views: 310

Answers (1)

David Pasztor
David Pasztor

Reputation: 54706

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)
}

Upvotes: 1

Related Questions