在Python中是否有等同于'Filter'函数的Swift?

Is there a Swift equivalent to the 'Filter' function in Python?

在 python 中,使用 'filter' 函数可以非常简单地从 string/list 中删除不需要的项目,该函数可以与 'lambda' 函数结合使用。在 python 中,它很简单:

a = "hello 123 bye-bye !!£$%$%"
b = list(filter(lambda x: x.isalpha(), a))
c = "".join(b)
print(c) #Which would print "hellobyebye"

有什么方法可以在 swift 中轻松复制它,而无需先转换为 unicode 然后检查 unicode 值是否在某个范围内?另外,swift里面有没有'lambda'之类的东西?

是的,在Swift中有一个等价的Filter函数:

Filter

The filter method takes a function (includeElement) which, given an element in the array, returns a Bool indicating whether the element should be included in the resulting array. For example, removing all the odd numbers from the numbers array could be done like this:

let numbers = [ 10000, 10303, 30913, 50000, 100000, 101039, 1000000 ]
let evenNumbers = numbers.filter { [=10=] % 2 == 0 }
// [ 10000, 50000, 100000, 1000000 ]

更多关于Map, Filter and Reduce in Swift