Swift Property Value Monitoring

Source: Internet
Author: User

You must be familiar with the observer pattern in object-c. Swift provides a simpler way to implement

When we need to assign values to the object's property values, we can use Willset and didset to observe the changes in the object's property values.


Let's look directly at an example. Create a class Student to monitor the property name

The first is the definition of the student class.

Class student{    init (name:string) {        username=name;    }        var username:string= "" {        willset{            println ("Student name Newvalue:\ (newvalue)")        }        didset{            println ("Student name Oldvalue:\ (oldValue)")}}            


And then we initialize the student and modify his username to try the effect.

  var student=student (name: "Zhang San")//Note that the time of initialization is        student.username= "Lisi" without invoking the monitoring method

Printing results are as follows


Student name Newvalue:lisi

Student name OldValue: Zhang San


It's easy, there's a problem to keep talking about.


Apple Development Group: 414319235 Welcome to join the Welcome discussion question

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

Swift Property Value Monitoring

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.