zoukankan      html  css  js  c++  java
  • [转]Swift中实现Observable机制

    猴子原创,欢迎转载。转载请注明: 转载自Cocos2Der-CSDN,谢谢! 
    原文地址: http://blog.csdn.net/cocos2der/article/details/51917539

    今天给别人讲个Observable的实现和使用场景,结合Observable-Swift github: https://github.com/slazyk/Observable-Swift 讲了半天貌似还没有特别明白,故写了个简易的实现,讲述了下Observable属性监控机制。

    //: Playground - noun: a place where people can play
    
    import UIKit
    import Foundation
    
    // MARK: - Observable
    class Observable<T> {
        // 定义block结构
        typealias Observer = T -> Void
    
        // 申明一个block,用于数据改变的执行
        private var observer: Observer?
    
        // 数据发生变更,则通过observer告知
        var value: T {
            didSet {
                observer?(value)
            }
        }
    
        init(_ v: T) {
            value = v
        }
    
        func observe(observer: Observer?) {
            self.observer = observer
            observer?(value)
        }
    }
    
    // MARK: - People
    struct PeopleModel {
        let firstName: Observable<String>
        let lastName: Observable<String>
    
        init(firstName: String, lastName: String) {
            self.firstName = Observable(firstName)
            self.lastName = Observable(lastName)
        }
    }
    
    // MARK: - Test
    
    // test1
    let people = PeopleModel(firstName: "sunny", lastName: "liu")
    people.firstName.observe {
        newValue in
        print("firstName changed: (newValue)")
    }
    people.lastName.observe {
        print("lastName changed: ($0)")
    }
    people.firstName.value = "sunny2"
    people.lastName.value = "liu2"
    
    // test2
    class House {
        let lableHouseName =  UILabel()
    
        init() {
    
        }
    
        var people: PeopleModel? {
            didSet {
                people?.firstName.observe{
                    [unowned self] in
                    self.lableHouseName.text = $0
                }
            }
        }
    }

    这样貌似容易理解了,O(∩_∩)O哈哈~

  • 相关阅读:
    msql查询指定日期
    NLP常见任务
    KTT条件及其理解
    距离度量--熵,KL散度,JS散度,GAN相关应用
    常见的激活函数
    分类问题的判别标准
    最大似然估计
    损失函数
    【ML-10】多分类及多标签分类算法
    【ML-9】支持向量机--实验scitit-learn SVM
  • 原文地址:https://www.cnblogs.com/linganxiong/p/5896996.html
Copyright © 2011-2022 走看看