Pan MluvĨí Pan MluvĨí - 1 year ago 90
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 Source

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) }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download