ios - 如何在 Swift 中创建自定义高阶函数,如 .maps() 或 .filter()

标签 ios swift dictionary higher-order-functions

我只是在寻找 swift 中高阶函数的内部实现,例如 map、filter、reduce。

根据苹果文档。

@inlinable public func map(_ transform: (Element) throws -> T) rethrows -> [T]

Returns an array containing the results of mapping the given closure over the sequence's elements.

例如;

var arr = [1,2,3,4,5]

print(arr.map({$0*5}))

输出将是

[5,10,15,20,25];

print(arr.map({String($0)}))

我只是想知道这里的计算基本上是如何工作的,或者高阶内部是如何工作的。您能否在这里帮助我,了解 map 在这里如何工作,例如如何处理值(相乘或转换为字符串)。

最佳答案

您可以像这样创建自定义 map 。在该序列下,您可以创建自己的高阶函数。

extension Sequence {

public func customMap2<T>(

    _ transform: (Element) -> T

    ) -> [T] {

    var result = [T]()

    for item in self {

        result.append(transform(item))

    }

    return result

   }

}

关于ios - 如何在 Swift 中创建自定义高阶函数,如 .maps() 或 .filter(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59705506/

相关文章:

iOS - 在后台播放 "called"时的铃声

arrays - 无法使用 '[AnyHashable : Any]' 类型的索引为 'Any?' 类型的值添加下标

ios - swift 3 以编程方式填充字典

android - Flutter - AppBar 底部小部件

ios - 更改swift4中while循环的声音文件

javascript - React Native 文本输入掩码

swift - ARKit – 为什么不再有 'ARPlaneDetection' 枚举?

ios - 打开带有对象的 View

swift - 可靠地使用 UICollectionView indexPath 访问字典键?

javascript - 在 JavaScript 中创建 "dictionary of dictionaries"的首选方法