【问题标题】:How can I create an Array method in Swift similar to sort, filter, reduce, and map?如何在 Swift 中创建类似于 sort、filter、reduce 和 map 的 Array 方法?
【发布时间】:2017-12-29 02:03:08
【问题描述】:

我有一个问题,正在研究闭包。

我想像数组类型一样制作数据类型闭包方法 .sort()、.filter()、.reduce()、.map()

但是我怎么能做这个东西。 它的数据类型不是一个类。


我想做

array.somemethod({closure})

不是

Somefunc(input: array, closure : { .... })

-

我可以在 swift 中创建数据类型方法吗?

否则,我只能使用 func 吗?

【问题讨论】:

  • Swift 中的大多数数据类型都是结构。数组、字符串、双精度、整数、日期。你到底想做什么?
  • @Leo Dabus 嗯...,我想要像 array.somemethod({closure}) 一样,而不是 Somefunc(input: array, closure : { .... })
  • 你只需要扩展数组并传递一个闭包作为你的方法参数。

标签: swift methods types closures


【解决方案1】:

你只需要扩展 Array 并传递一个闭包作为你的方法参数。假设您想创建一个变异方法来作为过滤器的反面(根据条件删除数组的元素):

extension Array {
    mutating func removeAll(where isExcluded: (Element) -> Bool)  {
        for (index, element) in enumerated().reversed() {
            if isExcluded(element) {
                remove(at: index)
            }
        }
    }
}

另一个扩展RangeReplaceableCollection的选项:

extension RangeReplaceableCollection where Self: BidirectionalCollection {
    mutating func removeAll(where predicate: (Element) throws -> Bool) rethrows {
        for index in indices.reversed() where try predicate(self[index]) {
            remove(at: index)
        }
    }
}

用法:

var array = [1, 2, 3, 4, 5, 10, 20, 30]
array.removeAll(where: {$0 > 5})
print(array)   // [1, 2, 3, 4, 5]

或使用尾随闭包语法

array.removeAll { $0 > 5 }

【讨论】:

    猜你喜欢
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多