Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot assign property in method of struct

Tags:

swift

In Swift, I'm trying to do the following:

struct Foo {
    var bar = 1

    func baz() {
        bar = 2
    }
}

Xcode reports the error Cannot assign to 'bar' in self on the line in the method.

Why? If I change the struct to a class, there's no error.

like image 853
dpassage Avatar asked Oct 19 '14 04:10

dpassage


2 Answers

If you want to modify the properties of the struct, mark the function as mutating.

struct Foo {
    var bar = 1

    mutating func baz() {
        bar = 2
    }
}
like image 134
Connor Avatar answered Sep 22 '22 08:09

Connor


The reason that you cannot assign to a struct's variable from within the struct itself is because instance methods of a struct cannot mutate instance variables. For this to work you need to add the keyword mutating before the declaration of the function.

This will give you the following code:

struct Foo {
    var bar = 1

    mutating func baz() {
        bar = 2
    }
}

The function baz() will now be able to mutate the instance variables of the struct.

like image 27
Swinny89 Avatar answered Sep 20 '22 08:09

Swinny89