简体   繁体   中英

Swift Combine: no `distinct` operator?

Seems like Combine (shipped with Xcode 11 beta 7) lacks adistinct operator?

Can anyone help me build one? :)

.removeDuplicates() is equivalent to .distinctUntilChanged()

You can do the following to get .distinct() .

@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)
extension Publisher where Self.Output : Equatable {
    public func distinct() -> AnyPublisher<Self.Output, Self.Failure> {
        self.scan(([], nil)) {
            $0.0.contains($1) ? ($0.0, nil) : ($0.0 + [$1], $1)
        }
        .compactMap { $0.1 }
        .eraseToAnyPublisher()
    }
}

嗯,我真傻,有一个叫做RemoveDuplicates ,它链接到方法removeDuplicates()

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