How can I create an Array method in Swift similar

2019-09-20 05:19发布

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条回答
叼着烟拽天下
2楼-- · 2019-09-20 05:28

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 }
查看更多
登录 后发表回答