当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Swift AsyncThrowingDropWhileSequence compactMap(_:)用法及代码示例


用法一

实例方法

compactMap(_:)

创建一个异步序列,将给定的闭包映射到异步序列的元素上,省略不返回值的结果。

声明

@preconcurrency func compactMap<ElementOfResult>(_ transform: @escaping (Self.Element) async -> ElementOfResult?) -> AsyncCompactMapSequence<Self, ElementOfResult>

返回值

一个异步序列,按顺序包含由 transform 闭包生成的非 nil 元素。

参数

transform

映射闭包。 transform 接受此序列的元素作为其参数,并返回相同或不同类型的转换值。

详述

使用 compactMap(_:) 方法转换从基本异步序列接收到的每个元素,同时丢弃闭包中的任何 nil 结果。通常,您使用它从一种类型的元素转换为另一种类型的元素。

在此示例中,名为 Counter 的异步序列生成从 15Int 值。提供给compactMap(_:) 方法的闭包接受每个Int 并从romanNumeralDict 字典中查找相应的String。因为 4 没有键,所以在这种情况下,闭包返回 nil,而 compactMap(_:) 从转换的异步序列中省略。


let romanNumeralDict: [Int : String] =
    [1: "I", 2: "II", 3: "III", 5: "V"]
    
let stream = Counter(howHigh: 5)
    .compactMap { romanNumeralDict[$0] }
for await numeral in stream {
    print("\(numeral) ", terminator: " ")
}
// Prints: I  II  III  V

可用版本

iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+

用法二

实例方法

compactMap(_:)

创建一个异步序列,将 error-throwing 闭包映射到基本序列的元素上,省略不返回值的结果。

声明

@preconcurrency func compactMap<ElementOfResult>(_ transform: @escaping (Self.Element) async throws -> ElementOfResult?) -> AsyncThrowingCompactMapSequence<Self, ElementOfResult>

返回值

一个异步序列,按顺序包含由 transform 闭包生成的非 nil 元素。当基本序列结束或transform 引发错误时,序列结束。

参数

transform

error-throwing 映射闭包。 transform 接受此序列的元素作为其参数,并返回相同或不同类型的转换值。如果transform 引发错误,则序列结束。

详述

使用 compactMap(_:) 方法转换从基本异步序列接收到的每个元素,同时丢弃闭包中的任何 nil 结果。通常,您使用它从一种类型的元素转换为另一种类型的元素。

在此示例中,名为 Counter 的异步序列生成从 15Int 值。提供给compactMap(_:) 方法的闭包接受每个Int 并从romanNumeralDict 字典中查找相应的String。由于 4 没有键,因此在这种情况下,闭包返回 nil,而 compactMap(_:) 从转换的异步序列中省略。当值为 5 时,闭包抛出 MyError ,终止序列。


let romanNumeralDict: [Int : String] =
    [1: "I", 2: "II", 3: "III", 5: "V"]


do {
    let stream = Counter(howHigh: 5)
        .compactMap { (value) throws -> String? in
            if value == 5 {
                throw MyError()
            }
            return romanNumeralDict[value]
        }
    for try await numeral in stream {
        print("\(numeral) ", terminator: " ")
    }
} catch {
    print("Error: \(error)")
}
// Prints: I  II  III  Error: MyError()

可用版本

iOS 13.0+, iPadOS 13.0+, macOS 10.15+, Mac Catalyst 13.0+, tvOS 13.0+, watchOS 6.0+

相关用法


注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 AsyncThrowingDropWhileSequence compactMap(_:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。