How to implement remove_if in swift (remove interrupts from array)?
Problem
Suppose I have an array of strings.
Using functional programming only (map, reduce, etc.), I want to create a new array that has no punctuation marks.
Let's assume there are no built-in punctuation marks (i.e. they will be on their own).
let test_arr = [ "This", "is", "a", "test", ";", "try", "it", "." ]
let punc = [ "!":true, ".":true, "?":true, ";":true ]
let new_arr = test_arr.remove_if { punc[ $0 ]? != nil } // how to implement?
Maybe something like this already exists? I had no luck with Google on Apple docs.
+3
source to share
1 answer
I think it is best to use filter () in conjunction with checking the current element against the NSCharacterSet puncuationCharacterSet (). This should do what you want.
let test_arr = [ "This", "is", "a", "test", ";", "try", "it", "." ]
let charSet = NSCharacterSet.punctuationCharacterSet()
let noPuncuation = test_arr.filter { $0.rangeOfCharacterFromSet(charSet, options: .LiteralSearch, range: nil)?.startIndex == nil }
println(noPuncuation) // [This, is, a, test, try, it]
As a side note, you can use the code in this answer to get a list of all characters in a given character set, or define your own character set like this.
let customCharset = NSCharacterSet(charactersInString: "!@#")
+3
source to share