Implementing the observable mechanism in swift

Source: Internet
Author: User

Monkey original, welcome reprint. Reproduced please specify: Reproduced from COCOS2DER-CSDN, thank you!
Original address: http://blog.csdn.net/cocos2der/article/details/51917539

Today to others to tell a Observable implementation and use of the scene, combined with Observable-swift Github:https://github.com/slazyk/observable-swift said half a day seems not particularly clear, Therefore wrote a simple realization, narrated the next observable attribute monitoring mechanism.

//: Playground-noun:a place where people can playImportUIKitImportFoundation//MARK:-ObservableClass Observable<T>{//define block structureTypealias Observer=T -Void    //Declare a block for the execution of data changes    Private varObserver:observer?    //Data changes, the Observer informs    varVALUE:T {DIDSET {Observer?(value)} } init (_ V:t) {value=V} func Observe (Observer:observer?) { Self.Observer=Observer Observer?(Value)}}//MARK:-Peoplestruct Peoplemodel { LetFirstname:observable<String>     LetLastname:observable<String>Init (firstName:String, LastName:String) { Self.FirstName=Observable (FirstName) Self.LastName=Observable (LastName)}}//MARK:-Test//Test1 LetPeople=Peoplemodel (firstName:"Sunny", LastName:"Liu") people.FirstName.Observe {NewValueinchPrint"FirstName changed: \ (newvalue)")}people.LastName.Observe {print ("LastName changed: \ ($)")}people.FirstName.Value= "Sunny2"People.LastName.Value= "LIU2"//Test2Class House { LetLablehousename=UILabel () init () {}varPeople:peoplemodel?{didset {people?.FirstName.observe{[unowned Self]In Self.lableHouseName.text = $}} }}

This seems easy to understand, O (∩_∩) o haha ~

Implementing the observable mechanism in swift

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.