【问题标题】:How to create custom higher order function like .maps() or .filter() works in Swift [closed]如何在 Swift 中创建像 .maps() 或 .filter() 这样的自定义高阶函数 [关闭]
【发布时间】:2020-04-29 12:14:48
【问题描述】:

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

根据苹果文档。

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

返回一个数组,其中包含将给定闭包映射到序列元素的结果。

例如;

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

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

输出将是

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

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

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

【问题讨论】:

    标签: ios swift dictionary higher-order-functions


    【解决方案1】:

    map 将闭包作为其唯一的输入参数,它将序列的单个元素转换为另一种类型。 map 遍历调用它的序列的所有元素,并对它们执行闭包,从而返回每个原始元素的转换值。

    对于您的具体示例,第一个简单地将 arr 的每个元素乘以 5,因此结果数组的每个元素将包含给定索引处的原始元素乘以 5。

    第二个示例简单地将每个Int 转换为String

    您可以查看 GitHub 上的 current implementation of Sequence.map,因为 Swift 是一种开源语言:

    @inlinable
      public func map<T>(
        _ transform: (Element) throws -> T
      ) rethrows -> [T] {
        let initialCapacity = underestimatedCount
        var result = ContiguousArray<T>()
        result.reserveCapacity(initialCapacity)
    
        var iterator = self.makeIterator()
    
        // Add elements up to the initial capacity without checking for regrowth.
        for _ in 0..<initialCapacity {
          result.append(try transform(iterator.next()!))
        }
        // Add remaining elements, if any.
        while let element = iterator.next() {
          result.append(try transform(element))
        }
        return Array(result)
      }
    

    【讨论】:

    • 感谢大卫的解释。您能否也让我知道,这里的 transform 将我的元素转换为 String 或乘以 5。对吗?
    • @VikashSinha 看看这个解释得很好hackingwithswift.com/articles/173/…
    【解决方案2】:

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

    extension Sequence {
    
    public func customMap2<T>(
    
        _ transform: (Element) -> T
    
        ) -> [T] {
    
        var result = [T]()
    
        for item in self {
    
            result.append(transform(item))
    
        }
    
        return result
    
       }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多