Swift屬性觀察者

來源:互聯網
上載者:User

標籤:swift屬性觀察者

    為了監聽屬性的變化,Swift提供了屬性觀察者,屬性觀察者能夠監聽儲存屬性的變化,即便變化前後的值不同,它們也能監聽到,但它們不能延遲儲存屬性和常量儲存屬性的變化


    Swift中的屬性觀察者主要有以下兩種:


    1、willSet:觀察者在修改之前調用;


    2、didSet:觀察者在修改之後調用;


    屬性觀察者的文法如下:


    物件導向類型 類型名 {

            var 儲存屬性 : 屬性資料類型 = 初始值 {

                willSet(新值){


}

                didSet(舊值){

                

}


}


}

        樣本

        

        class Employee{

            var no:Int = 0

            var name:String {

                willSet(NewNameValue){

                    println("員工name的新值:\(NewNameValue)")

}

                didSet(oldNameValue){

                    println("員工name的舊值:\(oldNameValue)")

}

}

                var job:String?

                 var  salary:Double=0

                 var depet:Department? 

}


        struct Department {

                var no : Int = 10 {

                    willSet{

                    println("部門編號新值:\(newValue))")

}

}

                    didSet{

                       println("部門編號舊值\(oldValue)")

}


}


本文出自 “平凡之路” 部落格,請務必保留此出處http://linjohn.blog.51cto.com/1026193/1622088

Swift屬性觀察者

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.