如何在Swift中创建类似于排序,过滤,缩小和映射的Array方法? [英] How can I create an Array method in Swift similar to sort, filter, reduce, and map?
问题描述
在研究封闭性时,我有一个问题.
I have a question, during study of closure.
我想要像数组类型那样使数据类型闭合方法 .sort()、. filter()、. reduce()、. map()
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.
我想做
array.somemethod({closure})
不是
Somefunc(input: array, closure : { .... })
-
我可以快速制作数据类型方法吗?
Can I make datatype method in swift?
否则,我只能使用func吗?
otherwise, I can use func only?
推荐答案
您只需要扩展Array并传递一个闭包作为方法参数即可.假设您想创建一个可变方法,使其与过滤器相反(根据条件删除数组的元素):
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)
}
}
}
}
扩展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]
或使用结尾闭包语法
array.removeAll { $0 > 5 }
这篇关于如何在Swift中创建类似于排序,过滤,缩小和映射的Array方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!