LoginSignup
1

More than 1 year has passed since last update.

Left side of mutating operator isn't mutable: 'self' is immutable

Last updated at Posted at 2021-05-04

以下のようなクイズの問題と答え、何問目かを示すquestionNumberを関数で変化させようとしたら
Left side of mutating operator isn't mutable: 'self' is immutable
というエラーが発生した。

import Foundation

struct QuizBrain {
    let quiz = [
        Question(q: "1 + 2 = 3", a: "True"),
    ]

    var questionNumber = 0
}

    func nextQuestion() {
        if questionNumber + 1 < quiz.count {
            questionNumber += 1
        } else {
            questionNumber = 0
        }
    }
}

funcの前にmutatingを書くことでエラーは回避された。
どうやら構造体内の関数ではquestionNumberは不変のため変更できないようだ。

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
1