swift 概念证明类型安全的RAC包装器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 概念证明类型安全的RAC包装器相关的知识,希望对你有一定的参考价值。

protocol ISubscriber {
    typealias Element

    func disposable() -> RACCompoundDisposable

    func sendNext(e: Element)
    func sendError(e: NSError)
    func sendCompleted()
}

/// Wraps RACSubscriber
class Subscriber<T: AnyObject> : ISubscriber {
    let subscriber: RACSubscriber

    init(wrapped: RACSubscriber) 
    {
        subscriber = wrapped
    }

    func disposable() -> RACCompoundDisposable
    {
        return subscriber.disposable
    }

    func sendNext(e: T)
    {
        subscriber.sendNext(e)
    }

    func sendError(e: NSError)
    {
        subscriber.sendError(e)
    }

    func sendCompleted()
    {
        subscriber.sendCompleted()
    }
}

/// Wraps RACSignal
class Signal<T: AnyObject> {
    let signal: RACSignal

    init(wrapped: RACSignal)
    {
        signal = wrapped
    }

    convenience init(didSubscribe: Subscriber<T> -> ())
    {
        return self.init(wrapped: RACSignal.create { racSubscriber in
            let subscriber = Subscriber<T>(wrapped: racSubscriber)
            didSubscribe(subscriber)
        })
    }

    //TODO -[RACSignal return:] could not be called here directly because Swift hates keywords as selectors, hence this suboptimal implementation
    convenience init(value: T)
    {
        return self.init(didSubscribe: { s in
            s.sendNext(value)
            s.sendCompleted()
        })
    }

    // operations

    func flatMap<U: AnyObject>(f: T -> Signal<U>) -> Signal<U>
    {
        return Signal<U>(wrapped: signal.flattenMap { value in
            return f(value as T).signal
        })
    }

    func map<U: AnyObject>(f: T -> U) -> Signal<U>
    {
        return Signal<U>(wrapped: signal.map { value in
            return f(value as T)
        })
    }

    func filter(p: T -> Bool) -> Signal<T>
    {
        return Signal(wrapped: signal.filter { value in
            return p(value as T)
        })
    }

    // subscription

    func subscribe(next: T -> ()) -> RACDisposable
    {
        return signal.subscribeNext { value in next(value as T) }
    }

    func subscribe(next: T -> (), completed: () -> ()) -> RACDisposable
    {
        return signal.subscribeNext(
            { value in next(value as T) },
            completed: { completed() }
        )
    }
}

以上是关于swift 概念证明类型安全的RAC包装器的主要内容,如果未能解决你的问题,请参考以下文章

Swift 属性包装器

Swift 属性包装器

Swift 属性包装器可以引用其包装的属性所有者吗?

如何在Swift中声明一个弱引用数组?

具有定制包装类型的柴油

在 Swift 属性包装器中公开字典