简体   繁体   中英

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

In python, it is incredibly simple to remove unwanted items from a string/list using the 'filter' function which can be used in conjunction with 'lambda' functions. in python, it's as simple as:

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

Is there any way to easily replicate this in swift without first converting to unicode and then checking if the unicode value is within a certain range? Also, are there any 'lambda' like things in swift?

Yes, there is an equivalant Filter function in Swift:

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 { $0 % 2 == 0 } // [ 10000, 50000, 100000, 1000000 ] 

More about Map, Filter and Reduce in Swift

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM