【问题标题】:mapAs, filterAs, subscribeNextAs for ReactiveCocoa 3.0mapAs, filterAs, subscribeNextAs 用于 ReactiveCocoa 3.0
【发布时间】:2015-10-17 00:06:12
【问题描述】:

在 Colin Eberhart 的 pdf 文件中看到他自己制作了这些扩展。他用 Swift 编写了 subscribeNextAs,但没有编写任何其他代码。

以下是否正确?

extension RACSignal {

    func subscribeNextAs<T>(nextClosure:(T) -> ()) -> () {
        self.subscribeNext {
        (next: AnyObject!) -> () in
            let nextAsT = next as! T
            nextClosure(nextAsT)
        }
    }

    func filterAs<T>(nextClosure:(T!) -> Bool) -> (RACSignal) {
            return self.filter {
                (next: AnyObject!) -> Bool in
                if(next == nil){
                    return nextClosure(nil)
                }else{
                    let nextAsT = next as! T
                    return nextClosure(nextAsT)
                }
            }
    }

    func mapAs<T>(nextClosure:(T!) -> AnyObject!) -> (RACSignal) {
            return self.map {
                (next: AnyObject!) -> AnyObject! in
                if(next == nil){
                    return nextClosure(nil)
                }else{
                    let nextAsT = next as! T
                    return nextClosure(nextAsT)
                }
            }
    }


}

【问题讨论】:

    标签: ios reactive-cocoa reactive-cocoa-3


    【解决方案1】:

    尽管您写的似乎是正确的,但 Colin Eberhart 的那些扩展是很久以前为 RAC v2 制作的,当时 RAC v3 还处于早期开发阶段。现在它已经是一个候选版本,那么为什么不使用它呢?它足够方便。 Xcode 会自动检测Signal 的类型

    intSignal
        |> filter { num in num % 2 == 0 }
        |> map(toString)
        |> observe(next: { string in println(string) })
    

    README.mdDocumentation folder 中的更多信息

    【讨论】:

    • 哇! “|>”是以前所有冗长代码的语法糖!?非常感谢你回答我的问题。你似乎是 ReactiveCocoa 的大师
    • 嗯,它不是语法糖,而是一个全新的架构。不再是RACSignal,而是Signal&lt;T,ErrorType&gt;map 不再是返回其他信号的实例方法,而是返回闭包的全局函数。 |&gt; 只是一个将这个闭包包裹在接收器周围的运算符。我只是在使用 ReactiveCocoa :)
    • questino @ReDetection ugh 候选版本集成到我的项目中真的很烦人。我按照他们的指示使用 xcode 将 .xcodeproject 文件放入我的文件夹中,并尝试使用“常规”选项卡中的“嵌入二进制文件”添加 ReactiveCocoa.framework,但它没有构建......你是这样手动完成的吗?使用 Carthage 要容易得多,但手动操作实在是太痛苦了
    • 我只将 Carthage 用于 ReactiveCocoa。无论如何,使用 Embed Binary 添加框架很奇怪——有“Link Binary With Libraries”,不是吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 2015-12-23
    • 2015-02-23
    • 1970-01-01
    相关资源
    最近更新 更多