3

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?

R21
  • 396
  • 2
  • 12
  • 2
    possible duplicate of [List comprehension in Swift](http://stackoverflow.com/questions/24003584/list-comprehension-in-swift) – TigerhawkT3 Aug 21 '15 at 19:07
  • Note: the list comprehension in the above link includes a filtering expression. – TigerhawkT3 Aug 21 '15 at 19:08
  • i'm not 100% sure on how this would work. could you elaborate? – R21 Aug 21 '15 at 19:11
  • The linked question and answers seem pretty clear to me, and I've been learning Swift for about five minutes (for this question). I think you need to spend some time with [the documentation](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/index.html) or a tutorial. – TigerhawkT3 Aug 21 '15 at 19:19
  • 1
    btw, `''.join(x for x in a if x.isalpha())`. There are situations where I use `map` and `filter`, but if you're using them *with a lambda* then the equivalent comprehension almost always reads better. – Steve Jessop Aug 21 '15 at 19:36

1 Answers1

5

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

Assem
  • 11,574
  • 5
  • 59
  • 97
  • What does the '$0' do? does this act as a placeholder for each individual list element? – R21 Aug 21 '15 at 19:14
  • 2
    Please see [the documentation on closures](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-ID94), under the section titled "Shorthand Argument Names." – TigerhawkT3 Aug 21 '15 at 19:16