0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Swift】didSetとwillSetを用いて値の変更時に処理を行う

Posted at

はじめに

  • Swiftの変数にはdidSetwillSetというプロパティオブザーバーがあり、変数の値が変更される前と後のタイミングで任意の処理を行うことが出来る機能が存在します。

didSet

  • 新しい変数の値がセットされたに呼び出される

didSet is called immediately after the new value is stored.

willSet

  • 新しい変数の値がセットされるに呼び出される

 willSet is called just before the value is stored.

コード

import Foundation


var ab = (99, 100, 101)

var before: Int = ab.1 {
    didSet {
        print("old: \(oldValue)")
    }
}

var after: Int = ab.1 {
    willSet {
        print("new: \(newValue)") // after = ab.2のセット前に更新
    }
}

print(before, after)

before = ab.0 
after = ab.2

print(before, after) // before = ab.0のセット後に更新

出力

100 100
old: 100
new: 101
99 101

引用

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?