LoginSignup
0
1

More than 3 years have passed since last update.

プロパティオブザーバ

Posted at

プロパティオブザーバとは

ストアドプロパティの値の変更を監視し、変更前と変更後に文を実行するものです。

基本構文

var プロパティ名 = 初期値 {
    willSet {
        プロパティの変更前に実行する文
        変更後の値には定数newValueとしてアクセスできる
    }

    didSet {
        プロパティの変更後に実行する文
    }
}

サンプルコード

struct Greeting {
    var to = "Yoshida" {
        willSet {
            print("willSet: (to: \(self.to), newValue: \(newValue))")
        }

        didSet {
            print("didSet: (to: \(self.to))")
        }
    }
}

var greeting = Greeting()
greeting.to = "Yamada"
// 出力
willSet: (to: Yoshida, newValue: Yamada)
didSet: (to: Yamada)
0
1
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
0
1