swiftclosures

Swift closure syntax


I have following code that work:

let obsScan = source.scan(0, accumulator: +)
let obsReduce = source.reduce(0, accumulator: +)

let obs = Observable.zip(obsScan, obsReduce) { scan, reduce in
        return "scan - \(scan), reduce - \(reduce)"
}

I want to rewrite it, using auto complete closure syntax, and i ended up with:

let obs = Observable.zip(obsScan, obsReduce, resultSelector: { (scan, reduce) -> _ in
         return "scan - \(scan), reduce - \(reduce)"
})

However, that code throw me multiple errors:

Contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored Consecutive statements on a line must be separated by ';' Expected expression

I can't understand why i use tab to autocomplete function with closure, and when i fill arguments i got an errors?

Whole function declared like that:

 public static func zip<O1, O2>(_ source1: O1, _ source2: O2, resultSelector: @escaping (O1.E, O2.E) throws -> RxSwift.Observable.E) -> RxSwift.Observable<RxSwift.Observable.E> where O1 : ObservableType, O2 : ObservableType

Solution

  • I'm not sure what are you waiting for. But this should work:

    let obs = Observable.zip(obsScan, obsReduce, resultSelector: { scan, reduce in
             return "scan - \(scan), reduce - \(reduce)"
    })