LoginSignup
15
15

More than 5 years have passed since last update.

Swift の変数やプロパティの値監視について

Posted at

変数でもプロパティでも書き方は変わらない

Sample


var piyo: String = "hoge" {
willSet{
    NSLog("now:%@", piyo) // set 前の値
    NSLog("new:%@", newValue) // set 予定の値
}
didSet{
    NSLog("now:%@", piyo) // set 後の値
    NSLog("old:%@", oldValue) // set 前の値
}
}

piyo = "fuga" // piyo を書き換える


実行結果

// willSet
now:hoge
new:fuga

// didSet
now:fuga
old:hoge

willSet

willSet は実際に値が set される前に呼ばれる、willSet 内では変数名(プロパティ名)で現在の値に、newValueで新しくセットされる予定の値にアクセスする事が出来る。

didSet

didSet は値が set された後に呼ばれる、didSet 内では変数名(プロパティ名)で set 後の値に、oldValueで set される前の値にアクセスする事が出来る。

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