LoginSignup
17
15

More than 5 years have passed since last update.

Swift プロパティを監視する(willSet、didSet)

Last updated at Posted at 2016-03-08

プロパティを監視するwillSet、didSetについて記載

標準的な書き方
willSetはプロパティの変更前に、didSetは変更後に呼ばれる

class Car {
    var type:String = "bike" {
        willSet {
            print("willSet type:" + type); //willSet type:bike
        }
        didSet {
            print("didSet type:" + type);  //didSet type:track
        }
    }
}

var obj:Car = Car()
obj.type = "track"

init 呼び出し時の変更では、willSet、didSetは呼ばれない

class Car {
    init() {
        type = "default"
        self.type = "track"
    }
    var type:String = "bike" {
        willSet {
            print("willSet type:" + type);  //
        }
        didSet {
            print("didSet type:" + type);  //
        }
    }
}
var obj = Car()

Dictionaryの中身も監視される(Arrayも)

//Dictionaryの中身も監視される
class Car {
    var partsStatus:Dictionary<String,String> = ["engine":"v8","tire":"bridgestone"]{
        willSet {
            print("willSet partsStatus"); //willSet partsStatus
        }
        didSet {
            print("didSet partsStatus"); //didSet partsStatus
        }
    }
}
var obj = Car()
obj.partsStatus.updateValue("v8", forKey: "engine")

オブジェクトの中身は監視されない

class Engine {
    var name = "v6"
}

class Car{
    var engine:Engine = Engine(){
        willSet{
            print("willSet engine.name:" + engine.name); //
        }
        didSet{
            print("didSet engine.name:" + engine.name); //
        }
    }
}
var obj = Car()
obj.engine.name = "v8"

以上

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