Swift中实现Observable机制

前端之家收集整理的这篇文章主要介绍了Swift中实现Observable机制前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

猴子原创,欢迎转载。转载请注明: 转载自Cocos2Der-CSDN,谢谢!
原文地址: http://www.jb51.cc/article/p-tdefgbcq-vc.html

今天给别人讲个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哈哈~

原文链接:https://www.f2er.com/swift/323365.html

猜你在找的Swift相关文章