5
5

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.

Infinite loop in getter

Posted at

Swiftでは簡単にプロパティのgetterとsetterが定義できる。

class BaseCounter {
    var counter: Int {
        get {
            println("This is get")
            return self.counter + 1
        }
        set {
            println("This is set")
        }
    }
    init() {
        counter = 0
    }
}

このような形でクラスの書くプロパティに対して、任意のgetterとsetterを定義できる。
ところがこれを呼ぶと大変なことになる。

let c = BaseCounter()
println(c.counter)

//
// This is get
// This is get
// This is get
// This is get
// This is get
// ... 永遠に続く

どうやらgetの中に書いてあるself.counterがまたさらにgetterを呼ぶためにこういうことになるみたい。サンプル見ても自分自身の参照をgetterの中には書いてないのでやめた方がいいみたい。
そのproperty自体を操作して返す場合にはgetterを定義しない方がいいということなのかな。

5
5
8

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?