Help us understand the problem. What is going on with this article?

Swiftのmutatingキーワードについて

More than 1 year has passed since last update.

struct, enumで自身の値を変更する場合、funcの前にmutatingキーワードを書く。
再代入が行われるため、mutatingなメソッドは定数に対しては実行できない。

extension Int {
    // mutatingがない場合、コンパイルエラー
    // left side of mutating operator isn't mutable: 'self' is immutable
    mutating func plusOne() {
        self += 1
    }
}

var a = 1
a.plusOne() //2

let b = 1
// letで宣言したためコンパイルエラー
// cannot use mutating member on immutable value: 'b' is a 'let' constant
b.plusOne()

structの場合、ストアドプロパティを変更する場合にもmutatingキーワードが必要。
(structのストアドプロパティの変更=構造体の値の変更のため)

struct MyStruct {
    var member: Int

    init(member: Int){
        self.member = member
    }

    mutating func plusOne() {
        self.member += 1
    }
}

let myStruct = MyStruct(member: 1)
// letで宣言したためコンパイルエラー
// cannot use mutating member on immutable value: 'myStruct' is a 'let' constant
myStruct.plusOne()
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away