Learning note for Swift language 11 (Willset and Didset)

Source: Internet
Author: User

The Willset and Didset features are used in the swift language to monitor property value changes other than initialization of properties

There's no need to say too much, just look at the code below and you'll get it quickly.

Copy Code
Import Foundation

Class People:nsobject
{
Normal properties
var firstname:string = ""
var lastname:string = ""
var nickname:string = ""

//计算属性var fullName:String{    get    {        return nickName + " " + firstName + " " + lastName    }}//带属性监视器的普通属性var age:Int = 0{    //我们需要在age属性变化前做点什么    willSet    {        println("Will set an new value \(newValue) to age")    }    //我们需要在age属性发生变化后,更新一下nickName这个属性    didSet    {        println("age filed changed form \(oldValue) to \(age)")        if age<10        {            nickName = "Little"        }else        {            nickName = "Big"        }    }}func toString() -> String{    return "Full Name: \(fullName) " + ", Age: \(age) "}

}

var me = people ()
Me.firstname = "Zhang"
Me.lastname = "San"
Me.age = 20

println (me.tostring ())

/* Program Output
Would set an new value
Age filed changed form 0 to 20
Full Name:big Zhang San, age:20
*/

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Learning note for Swift language 11 (Willset and Didset)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.