Swift Combine — Operators(常用Filtering类操作符介绍)

2024-06-20 23:28

本文主要是介绍Swift Combine — Operators(常用Filtering类操作符介绍),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

  • filter(_: )
  • tryFilter(_: )
  • compactMap(_: )
  • tryCompactMap(_: )
  • removeDuplicates()
  • first(where:)
  • last(where:)

Combine中对 Publisher的值进行操作的方法称为 Operator(操作符)。 Combine中的 Operator通常会生成一个 Publisher,该 Publisher处理传入事件,对其进行转换,然后将更改后的事件发送给 Subscriber

本篇文章主要介绍一下过滤这一类的操作符。

filter(_: )

filter操作符主要用户过滤数据,比如下面的数据中,将大于5的数输出。

func filterSample() {let intArray = [1, 2, 3, 4, 5, 6, 7, 8, 9]_ = intArray.publisher.filter {$0 > 5}.sink { value inprint("value is : \(value)")}
}

输出为:

value is : 6
value is : 7
value is : 8
value is : 9

tryFilter(_: )

使用tryFilter(_:)来过滤在抛出错误的闭包中求值的元素。如果闭包抛出错误,则Publisher将因该错误而失败终止。

func tryFilterSample() {struct ZeroError: Error {}let intArray = [1, 2, 3, 4, 5, 6, 0, 8, 9]_ = intArray.publisher.tryFilter {if $0 == 0 {throw ZeroError()} else {return $0 > 5}}.sink(receiveCompletion: { completion inprint("Received completion: \(completion)")}, receiveValue: { value inprint("Received value: \(value)")})
}

tryFilter闭包接收到0时,抛出错误,整个Publisher链结束。上面输出结果为:

Received value: 6
Received completion: failure((extension in CombineLearning_PreviewReplacement_OperatorDemo_1):CombineLearning.OperatorViewModel.(unknown context at $1055a3cdc).(unknown context at $1055a3ce8).ZeroError())

compactMap(_: )

CombinecompactMap(_:)操作符的功能与Swift标准库中的compactMap(_:)类似。
Combine中的compactMap(_:)操作符移除Publisher流中的nil元素,并将非nil元素重新发布给下游订阅者。

func compactMapSample() {let numbers = (0...5)let romanNumeralDict: [Int : String] = [1: "one", 2: "two", 3: "three", 5: "five"]_ = numbers.publisher.compactMap { romanNumeralDict[$0] }.sink { print("\($0)", terminator: " ") }
}

当通过key为4的值的时候为nil了,所以这里将nil去除了。
输出结果为:

one two three five 

tryCompactMap(_: )

tryCompactMap(_: )相比compactMap(_:)除了都能去除nil外,前者还能在闭包内抛出错误。
如果闭包抛出错误,则Publisher流将因该错误而失败终止。

  func tryCompactMapSample() {struct ParseError: Error {}func romanNumeral(from: Int) throws -> String? {let romanNumeralDict: [Int : String] =[1: "one", 2: "two", 3: "three", 4: "four", 5: "five"]guard from != 0 else { throw ParseError() }return romanNumeralDict[from]}let numbers = [6, 5, 4, 3, 2, 1, 0]_ = numbers.publisher.tryCompactMap { try romanNumeral(from: $0) }.sink(receiveCompletion: { print ("\($0)") },receiveValue: { print ("\($0)", terminator: " ") })}

在上面代码中,当取key为6的元素时为nil,这个nil没有继续往下发送。当取key为0的元素时,抛出了错误,随后Publisher流结束。

输出结果为:

five four three two one failure((extension in CombineLearning_PreviewReplacement_OperatorDemo_1):CombineLearning.OperatorViewModel.(unknown context at $104a0bbec).(unknown context at $104a0bbf8).ParseError())

removeDuplicates()

有些时候下游的订阅者不希望收到重复的数据,那么用removeDuplicates方法可以去除重复数据。

func removeDuplicatesSample() {let intArray = [1, 1, 3, 5, 5, 6, 7, 8, 9]_ = intArray.publisher.removeDuplicates().sink { value inprint("value is : \(value)")}
}

上面代码中将数组中重复的数据去除,然后输出。
输出为:

value is : 1
value is : 3
value is : 5
value is : 6
value is : 7
value is : 8
value is : 9

另外需要注意removeDuplicates操作符不会将Publisher作为一个集合去排重,而是随着时间根据上下接收到的数据排重,如果相同的数据不挨着,那么不会认为是重复的。

func removeDuplicatesSample() {let intArray = [1, 1, 3, 5, 5, 6, 7, 1, 5]_ = intArray.publisher.removeDuplicates().sink { value inprint("value is : \(value)")}
}

上面数组中在末尾又添加了1和5,看看输出结果:

value is : 1
value is : 3
value is : 5
value is : 6
value is : 7
value is : 1
value is : 5

first(where:)

first(where:)操作符和filter操作符很相似,filter是找出所有满足条件的数据,而first(where:)操作符是找出第一个满足条件的数据。

func firstWhereSample() {let intArray = [1, 2, 3, 3, 5, 6, 7, 8, 9]_ = intArray.publisher.first {$0 > 5}.sink(receiveCompletion: { completion inprint("Received completion")}, receiveValue: { value inprint("Received value: \(value)")})
}

比如上面代码找出第一个大于5的数据,结果如下:

Received value: 6
Received completion

last(where:)

last(where:)first(where:)操作符正好相反, last(where:)操作符查找符合条件的最后一个数据。

func lastWhereSample() {let intArray = [1, 5, 3, 7, 2, 6, 4, 8, 9]_ = intArray.publisher.last {$0 < 6}.sink(receiveCompletion: { completion inprint("Received completion")}, receiveValue: { value inprint("Received value: \(value)")})
}

上面代码找出小于6的最后一个元素,输出结果为:

Received value: 4
Received completion

如果是找出大于6的最后一个元素,输出结果为:

Received value: 9
Received completion

最后,希望能够帮助到有需要的朋友,如果觉得有帮助,还望点个赞,添加个关注,笔者也会不断地努力,写出更多更好用的文章。

这篇关于Swift Combine — Operators(常用Filtering类操作符介绍)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/1079557

相关文章

Spring Security介绍及配置实现代码

《SpringSecurity介绍及配置实现代码》SpringSecurity是一个功能强大的Java安全框架,它提供了全面的安全认证(Authentication)和授权(Authorizatio... 目录简介Spring Security配置配置实现代码简介Spring Security是一个功能强

JSR-107缓存规范介绍

《JSR-107缓存规范介绍》JSR是JavaSpecificationRequests的缩写,意思是Java规范提案,下面给大家介绍JSR-107缓存规范的相关知识,感兴趣的朋友一起看看吧... 目录1.什么是jsR-1072.应用调用缓存图示3.JSR-107规范使用4.Spring 缓存机制缓存是每一

Python将字符串转换为小写字母的几种常用方法

《Python将字符串转换为小写字母的几种常用方法》:本文主要介绍Python中将字符串大写字母转小写的四种方法:lower()方法简洁高效,手动ASCII转换灵活可控,str.translate... 目录一、使用内置方法 lower()(最简单)二、手动遍历 + ASCII 码转换三、使用 str.tr

Spring Boot 常用注解整理(最全收藏版)

《SpringBoot常用注解整理(最全收藏版)》本文系统整理了常用的Spring/SpringBoot注解,按照功能分类进行介绍,每个注解都会涵盖其含义、提供来源、应用场景以及代码示例,帮助开发... 目录Spring & Spring Boot 常用注解整理一、Spring Boot 核心注解二、Spr

Java中 instanceof 的用法详细介绍

《Java中instanceof的用法详细介绍》在Java中,instanceof是一个二元运算符(类型比较操作符),用于检查一个对象是否是某个特定类、接口的实例,或者是否是其子类的实例,这篇文章... 目录引言基本语法基本作用1. 检查对象是否是指定类的实例2. 检查对象是否是子类的实例3. 检查对象是否

Java中的内部类和常用类用法解读

《Java中的内部类和常用类用法解读》:本文主要介绍Java中的内部类和常用类用法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录内部类和常用类内部类成员内部类静态内部类局部内部类匿名内部类常用类Object类包装类String类StringBuffer和Stri

MySQL连接池(Pool)常用方法详解

《MySQL连接池(Pool)常用方法详解》本文详细介绍了MySQL连接池的常用方法,包括创建连接池、核心方法连接对象的方法、连接池管理方法以及事务处理,同时,还提供了最佳实践和性能提示,帮助开发者构... 目录mysql 连接池 (Pool) 常用方法详解1. 创建连接池2. 核心方法2.1 pool.q

Spring Boot 常用注解详解与使用最佳实践建议

《SpringBoot常用注解详解与使用最佳实践建议》:本文主要介绍SpringBoot常用注解详解与使用最佳实践建议,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录一、核心启动注解1. @SpringBootApplication2. @EnableAutoConfi

SQL常用操作精华之复制表、跨库查询、删除重复数据

《SQL常用操作精华之复制表、跨库查询、删除重复数据》:本文主要介绍SQL常用操作精华之复制表、跨库查询、删除重复数据,这些SQL操作涵盖了数据库开发中最常用的技术点,包括表操作、数据查询、数据管... 目录SQL常用操作精华总结表结构与数据操作高级查询技巧SQL常用操作精华总结表结构与数据操作复制表结

JavaScript时间戳与时间的转化常用方法

《JavaScript时间戳与时间的转化常用方法》在JavaScript中,时间戳(Timestamp)通常指Unix时间戳,即从1970年1月1日00:00:00UTC到某个时间点经过的毫秒数,下面... 目录1. 获取当前时间戳2. 时间戳 → 时间对象3. 时间戳php → 格式化字符串4. 时间字符