66
40

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-03-20

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()
66
40
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
66
40

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?