简体   繁体   中英

How Does RXSwift combineLatest Use, What Looks Like, An Anonymous Class In A Closure And Handle Additional Parameters

So far as I understand it, Swift does not support anonymous classes.

I am working with an RXSwift codebase and there is a block of code I cannot fully grasp what is going on.

Here is the block:

    sections = Observable.combineLatest(observable1,
                                        observable2,
                                        observable3)
                                        {
                                            (arg1: $1,
                                            arg2: $0.0,
                                            arg3: $0.1,
                                            arg4: $2)
                                        }
                .map { arg1, arg2, arg3, arg4 -> [Section] in
                    // Do Stuff
                 }

The issue I have is the block where it converts the combineLatest into this, what looks like, anonymous class.

When I look at the signature for combineLatest it shows:

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

So as I read it, the @escaping closing takes in 3 arguments via the @escaping (O1.E, O2.E, O3.E)

It seems like a new anonymous object is being created, and its one with 4 arguments instead of 3.

Could you perhaps explain how a new observable of a seemingly anonymous class (which I don't fully understand as being possible) is being created, and being created with 4 arguments instead of 3?

The (arg1: $1, arg2: $0.0, arg3: $0.1, arg4: $2) part inside the closure creates a Tuple. A tuple is a group of multiple values of any type. Each element of a tuple can have a name, but they always can be accessed by number. In your example the tuple has 4 elements with the names arg1, arg2, arg3 and arg4. The elements of a tuple can have any type.

The syntax to create tuples is a list of comma-separated values with optional names inside parenthesis:

 let a = (1, "hello", true)
 let b = (first: 1, second: "hello", true)

To access the values of a tuple you use a . followed by the name or index:

 print(a.0, a.1, a.2)
 print(b.first, b.second, b.2)
 let x = b.0 

Note that you can also use the index, even if the element is named.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM