Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Syntax on |> and .~

Tags:

syntax

swift

There is some Swift syntax that I don't understand...

let creator = .template |> User.lens.avatar.small .~ ""

Can someone tell me what the |> and .~ syntax do? I also see %~ used.

If you can point out the location in the Swift documentation I would appreciate it. It's been difficult searching using these characters. I would like to see the full array of symbols.

like image 910
Christopher Avatar asked Jun 29 '26 09:06

Christopher


1 Answers

Stream Pipelining

Streams can be composed by using |> stream-pipelining operator and Stream Operations.

For example, a very common incremental search technique using searchTextStream will look like this:

let searchResultsStream: Stream<[Result]> = searchTextStream
    |> debounce(0.3)
    |> distinctUntilChanged
    |> map { text -> Stream<[Result]> in
        return API.getSearchResultsStream(text)
    }
    |> switchLatestInner

There are some scenarios (e.g. repeat()) when you want to use a cloneable Stream<T>.Producer (Void -> Stream<T>) rather than plain Stream<T>. In this case, you can use |>> streamProducer-pipelining operator instead.

// first, wrap stream with closure
let timerProducer: Void -> Stream<Int> = {
    return createTimerStream(interval: 1)
        |> map { ... }
        |> filter { ... }
}

// then, use `|>>`  (streamProducer-pipelining operator)
let repeatTimerProducer = timerProducer |>> repeat(3)

But in the above case, wrapping with closure will always become cumbersome, so you can also use |>> operator for Stream & Stream Operations as well (thanks to @autoclosure).

let repeatTimerProducer = createTimerStream(interval: 1)
    |>> map { ... }
    |>> filter { ... }
    |>> repeat(3)
like image 199
Amadeu Cavalcante Filho Avatar answered Jul 01 '26 22:07

Amadeu Cavalcante Filho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!