Notes for swift language 11 (willSet and didSet) and willsetdidset

Source: Internet
Author: User

Notes for swift language 11 (willSet and didSet) and willsetdidset

The willSet and didSet features are used in Swift to monitor attribute value changes except initialization.

You don't need to talk too much. You can quickly understand the following code.

Copy code
Import Foundation

Class People: NSObject
{
// Common attributes
Var firstName: String = ""
Var lastName: String = ""
Var nickName: String = ""

// Calculate the property var fullName: String {get {return nickName + "" + firstName + "" + lastName }}// common property var age with property monitor: int = 0 {// What do we need to do before the age attribute changes willSet {println ("Will set an new value \ (newValue) to age ")} // After the age attribute changes, update the didSet {println ("age filed changed form \ (oldValue) to \ (age)") attribute of nickName )") 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
Will set an new value 20 to age
Age filed changed form 0 to 20
Full Name: Big Zhang San, Age: 20
*/

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.