Swift 4.1 用于惰性集合的 compactMap

Swift 4.1 compactMap for lazy collections

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

let optionalIntegers : [Int?] = [1, 2, nil, 3, 4, nil, nil, 5]
optionalIntegers.lazy.flatMap { [=11=] }.forEach { print("Item \([=11=] * 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.