Evgeniy Kleban
Evgeniy Kleban

Reputation: 6940

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

Upvotes: 1

Views: 417

Answers (2)

JK Bot
JK Bot

Reputation: 37

It appears like the compiler believes that you are requesting a Tuple. You do not need to redeclare the typings especially since you are saying that you want to return nothing(ie. Void) from your closure. You can also drop the naming altogether like so;

let obs = Observable.zip(obsScan, obsReduce) { "scan - \($0), reduce - \($1)" }

Upvotes: 1

Vyacheslav
Vyacheslav

Reputation: 27211

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)"
})

Upvotes: 2

Related Questions