gpt4 book ai didi

arrays - 用于惰性集合的 Swift 4.1 compactMap

转载 作者:可可西里 更新时间:2023-11-01 00:39:12 26 4
gpt4 key购买 nike

在 Swift 4.1 之前,我使用 flatMap 从集合中删除 nil 值。现在此方法已弃用,我需要将其替换为 compactMap。有时我使用带有惰性集合的 flatMap 来优化我的代码,就像这样:

let optionalIntegers : [Int?] = [1, 2, nil, 3, 4, nil, nil, 5]
optionalIntegers.lazy.flatMap { $0 }.forEach { print("Item \($0 * 10)") }

如果我使用 compactMap 而不是 flatMap 会有同样的效果吗?在方法 lazy 的文档中,我发现仅引用了 mapfilter

最佳答案

是的,完全一样。他们只是决定消除 flatMap 函数的歧义,并将其中一个重命名为 compactMap 以免混淆开发人员。

提案如下:Introduce Sequence.compactMap(_:)

We propose to deprecate the controversial version of a Sequence.flatMap method and provide the same functionality under a different, and potentially more descriptive, name.

enter image description here

关于arrays - 用于惰性集合的 Swift 4.1 compactMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49916730/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com