Reputation: 6136
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
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