在Swift中搜索字符串中的子字符串不起作用

时间:2016-09-29 06:32:44

标签: ios swift string autocomplete nsstring

我在建议数组中匹配一个子字符串来制作自动填充文本字段。

func searchAutocompleteEntriesWithSubstring(substring: String)
{
    autocompleteUrls.removeAll(keepCapacity: false)

    for curString in countries
    {
        let myString:NSString! = curString as NSString

        let substringRange :NSRange! = myString.rangeOfString(substring)

        if (substringRange.location  == 0)
        {
            autocompleteUrls.append(curString)
        }
    }

    autocompleteTableView.reloadData()

}

但如果我正在寻找的国家是印度,我开始在" ndia"中搜索,它没有得到建议,它也应该得到它。

1 个答案:

答案 0 :(得分:3)

改为使用谓词:

let countries = ["india", "japan", "Indonesia", "bangladesh", "Australia"];

let predicate = NSPredicate(format: "SELF contains[c] %@", "ndia")

let autocompleteUrls = countries.filter { predicate.evaluateWithObject($0) }

print(autocompleteUrls) // output: ["india"]