j0h4nn3s j0h4nn3s - 1 year ago 251
Swift Question

Cannot use mutating member on immutable value of type

I have following struct:

public protocol SuperModel {
// empty protocol
struct ModelOne: SuperModel {
struct SubModelOne {
var someVar: Double
var othervar: Double?
var sub: SubModelOne?
mutating func setSub(sub: SubModelOne) {
self.sub = sub

In my class, I want to use this struct like that:

final class SomeClass: SuperClass {
var data: SuperModel
init() {
self.data = ModelOne()
func someFunc() {
(self.data as! ModelOne).setSub(ModelOne.SubModelOne(someVar: 2, otherVar: 1))

I get following error:
Cannot use mutating member on immutable value of type 'ModelOne'
. Why is that so and how can I fix this?

Answer Source

When you apply type casting to value types (such structs), if succeed, you receive immutable copy of requested value:

(self.data as! ModelOne) // this is copy of data

The only way (as known to me) how you can mutate values that need to be casted - reassign value (as @Sahil Beri pointed you need declare variable):

func someFunc() {
    if var data = data as? ModelOne {
        data.setSub(ModelOne.SubModelOne(someVar: 2, otherVar: 1))
        self.data = data // you can do this since ModelOne conforms to SuperModel
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download