包含字符串数组的Swift Filter数组

时间:2016-12-23 14:26:21

标签: ios swift

我想过滤一个包含字符串数组的数组。

我的代码是:

if(!(searchString?.isEmpty)!) {
    shouldShowSearchResults = true

    // Filter the data array and get only those countries that match the search text.
    filteredPlazaDictionary = plazaDictionary.filter({ (match) -> Bool in
        let matchText: NSString = match[1] as NSString
        return (matchText.range(of: searchString!, options: NSString.CompareOptions.caseInsensitive).location) != NSNotFound
    })
}

此处filteredPlazaDictionary[[String]]plazaDictionary[[String]]我希望将plazaDictionary内的每个数组[1]与searchString匹配。请帮助。

1 个答案:

答案 0 :(得分:3)

我会写这样的东西,我想......

// make it a function that takes everything it needs and returns a result array
func filteredCountryArray(countryArray: [[String]], searchString: String) -> [[String]] {
    guard !searchString.isEmpty else {
        // search string is blank so return entire array...
        return countryArray
    }

    // Filter the data array and get only those countries that match the search text.
    return countryArray.filter { match in
        // check array is long enough to get [1] out of it
        guard match.count >= 2 else {
            return false
        }

        let matchText = match[1]
        return matchText.range(of: searchString, options: .caseInsensitive) != nil
    }
}

plazaDictionary是一个非常奇怪的名称,可以赋予数组。它是一个数组,而不是字典。

这里你应该做的是创建一些数据对象(结构,类,枚举等......),它们以比嵌套数组更好的格式保存数据。

这应该做你现在想做的事。

修改

考虑到另一个,我也会将serachString和数组更改为输入参数......