如何以类似于排序,过滤,减少和映射类似的Swift创建数组方法



我有一个问题,在闭合研究期间。

我想要像数组类型一样制作数据型封闭方法 .sort(),.filter(),.Reduce(),.map()

但是我该怎么做。它的数据类型不是类。


我想制作

array.somemethod({closure})

不是

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

-

我可以在Swift中做数据类型方法吗?

否则,我只能使用func?

您只需要扩展数组并将闭合作为方法参数传递。可以说,您想创建一种突变方法,以作为过滤器的相反(根据条件删除数组的元素):

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 }

最新更新