How can I create an Array method in Swift similar to sort, filter, reduce, and map?

泄露秘密 提交于 2019-12-13 08:44:53

问题


I have a question, during study of closure.

I want make datatypes closure method like in array types .sort(), .filter(), .reduce(), .map()

But how can I make this things. Its datatype not a class.


I want make

array.somemethod({closure})

not a

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

-

Can I make datatype method in swift?

otherwise, I can use func only?


回答1:


You just need extend Array and pass a closure as your method argument. Lets say you would like to create a mutating method to work as the opposite of filter (to remove elements of your array based on a condition):

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

Another option extending 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)
        }
    }
}

Usage:

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

or using trailing closure syntax

array.removeAll { $0 > 5 }


来源:https://stackoverflow.com/questions/48016542/how-can-i-create-an-array-method-in-swift-similar-to-sort-filter-reduce-and-m

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!