Cannot assign property in method of struct

前端 未结 2 1300
一整个雨季
一整个雨季 2020-11-27 23:44

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

struct Foo {
    var bar = 1

    func baz() {
        bar = 2
    }
}

Xcode reports the error <

2条回答
  •  孤街浪徒
    2020-11-28 00:07

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

提交回复
热议问题