Pan MluvĨí Pan MluvĨí - 2 years ago 106
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 {
print("removed \(keywordsArr[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