Swift keyword Willset and didset

Source: Internet
Author: User

Here's an explanation from Apple that when setting a new value for a property, you can do some processing before and after setting it, and these two keywords are like monitoring the property changes.

If you don ' t need to compute the property but still need to provide code that's run before and after setting a new value, Use willSet and didSet . For example, the class below ensures and the side length of its triangle are always the same as the side length of its squ Is.

Code description

Class man:nsobject{

var Isyoung:bool

var name:string = "Anonymous"
{

willset{

println ("would set name to \ (name)")
}

didset{

println ("did set name from \ (oldValue) to \ (name)")
}
}

var age:int = 0{
willset{
println ("would set age to \ (age)")
}

didset{
println ("did set age from \ (oldValue) to \ (age)")
If age < 18{
Isyoung = True
}
else{
Isyoung = False
}
}
}
For an attribute variable that does not have an initial value set, it is initialized when it is created
Init (Isyong:bool) {
Self.isyoung = Isyong

Super.init ()
}

}

Let Gentleman:man = Mans (Isyong:false)
Gentleman.name = "Zhang San"
Gentleman.age = 17
Gentleman.isyoung

Output Result:

Would set name to anonymous
Did set name from anonymous to Zhang San
Would set age to 0
Did set age from 0 to 17

Swift keyword 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.