RxSwift toArray不使用泛型参数进行编译

时间:2016-09-20 13:09:06

标签: swift generics reactive-programming rx-swift

使用泛型时,RxSwift toArray对我不起作用:

struct SaveModelsCommand<M> where M:Model {

    let models:[M]

    func create() -> Observable<[M]> {

        let cloudKitRecords:[CKRecord] = models.map({ 
            // convert models to CKRecords
            ... 
        })

        return SaveRecordsCommand(cloudKitRecords)
            .createObservable()
            .flatMap({ savedRecords in
                // convert array to multiple emissions so we can iterate it
                return Observable.from(savedRecords)
            })
            .flatMap({ (record:CKRecord) -> M in
                // convert CKRecord back to a model (aka M)
                ... create model (e.g. Member) ...
                return model
            })
            // convert back to a single emission (array)
            .toArray() // <<<<< ERROR
    }
}

这是错误:

  

无法转换'Observable&lt; [M.E]&gt;'类型的返回表达式(又名'Observable&gt;')返回类型'Observable&lt; [M]&gt;' (又名'Observable&gt;')

我在返回类型中看到的唯一区别是M.E vs M

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

flatMap期望关闭返回Observable<M>,而不只是普通M

.flatMap({ (record:CKRecord) -> Observable<M> in
    // convert CKRecord back to a model (aka M)
    //... create model (e.g. Member) ...
    return Observable.just(model)
})

或者,您可以使用map并返回M

.map({ (record:CKRecord) -> M in
    // convert CKRecord back to a model (aka M)
    //... create model (e.g. Member) ...
    return model
})