Combine操作符Filtering示例


2天前 3次点击 来自 移动端

标签: Swift

Filtering 过滤

数据过滤很好理解,过滤不符合要求的数据

compactMap/tryCompactMap

保留非空数据,支持返回可选类型

_ = ["123", nil, "456"]
    .publisher
    .compactMap { value -> Int? in
        guard let v = value else {
            return nil
        }
        return Int(v)
    }
    .sink(receiveCompletion: { _ in
        print("Finished")
    }, receiveValue: { someValue in
        print(someValue)
    })

filter/tryFilter

_ = [5, 10, 25]
    .publisher
    .filter { value in
        value > 8
    }
    .sink(receiveCompletion: { _ in
        print("Finished")
    }, receiveValue: { someValue in
        print(someValue)
    })

removeDuplicates/tryRemoveDuplicates

数据去重

_ = [1, 1, 1, 2, 2, 3]
    .publisher
    .removeDuplicates()
    .sink(receiveCompletion: { _ in
        print("Finished")
    }, receiveValue: { someValue in
        print(someValue)
    })

如果Student没有实现Equatable协议则直接传入闭包指定去重规则即可

let students = [Student(age: 20, score: 80),
                Student(age: 20, score: 90),
                Student(age: 21, score: 90)]

_ = students
    .publisher
    .removeDuplicates(by: { first, second in
        first.age == second.age
    })
    .sink(receiveCompletion: { _ in
        print("Finished")
    }, receiveValue: { someValue in
        print(someValue)
    })

replaceError/replaceEmpty/replaceNil

这3个操作符作用类似,用于指定默认值

其中replaceError(0)用于指定替换错误值为0,其类似:

.catch { err in
    return Just(0)
}

replaceEmpty空数据流,pipline在接收到.finish事件前没有任何数据即为空数据流,可指定返回一个默认值

replaceNil同上,用于替换nil值

Made with in Shangrao,China By Devler.

Copyright © Devler 2012 - 2022

赣ICP备19009883号-1