Pan MluvĨí Pan MluvĨí - 5 months ago 24
Swift Question

Swift: Search string in sentence in Array

I am developing search textfield. I have an array of Strings that looks like this....

var keywords:[String] = ["dance, music and hippo", "apple juice, tomato"]


I tried to use function contains but its not doing well.

for i in 0..<keywordsArr.count {
if(!keywordsArr[i].contains(searchTextField.text!)){
print("removed \(keywordsArr[i])")
keywordsArr.removeAtIndex(i)
}
}


this is extension that i am using.

extension String {

func contains(find: String) -> Bool{
return self.rangeOfString(find) != nil
}
}


the result should be i am calling function with text: "music" and it should return index of that string

Answer

You can achieve this very succinctly, using filter, which returns an array with only elements for which the closure holds. You should also use optional binding to avoid using a force unwrap of searchTextField.text

if let text = searchTextField.text {
    keywordsArr = keywordsArr.filter { $0.contains(text) }
}