过滤字符串数组,包括“喜欢”条件

时间:2015-12-29 13:17:40

标签: ios arrays swift string filter

如果我的主阵列是["Hello","Bye","Halo"],而我正在搜索"lo",它会将数组仅过滤到["Hello", "Halo"]

这是我尝试过的:

 let matchingTerms = filter(catalogNames) {
        $0.rangeOfString(self.txtField.text!, options: .CaseInsensitiveSearch) !=  nil
    }

它抛出

Type of expression is ambiguous without more context

有什么建议吗?

7 个答案:

答案 0 :(得分:61)

改为使用contains

let arr = ["Hello","Bye","Halo"]
let filtered = arr.filter { $0.contains("lo") }
print(filtered)

输出

  

["您好"," Halo"]

感谢@ user3441734指出该功能当然仅在import Foundation

时才可用

答案 1 :(得分:25)

  

在Swift 3.0中

let terms = ["Hello","Bye","Halo"]

var filterdTerms = [String]()


func filterContentForSearchText(searchText: String) {
    filterdTerms = terms.filter { term in
        return term.lowercased().contains(searchText.lowercased())
    }
}


filterContentForSearchText(searchText: "Lo")
print(filterdTerms)

<强> 输出

["Hello", "Halo"]

答案 2 :(得分:5)

Swift 3.1

let catalogNames = [ "Hats", "Coats", "Trousers" ]
let searchCatalogName = "Hats"

let filteredCatalogNames = catalogNames.filter { catalogName in 
    return catalogName.localizedCaseInsensitiveContains(searchCatalogName)
}

print(filteredCatalogNames)

答案 3 :(得分:3)

我的尝试...

let brands = ["Apple", "FB", "Google", "Microsoft", "Amazon"]

let b = brands.filter{(x) -> Bool in 
(x.lowercased().range(of: "A".lowercased()) != nil)
}
print(b) //["Apple", "Amazon"]

答案 4 :(得分:2)

您还需要与NSNotFound进行比较。 rangeOfString:options的文档说:

  

NSRange结构,在第一次出现的aString中给出接收器中的位置和长度,以掩码中的选项为模。如果找不到aString或为空(@&#34;&#34;),则返回{NSNotFound,0}。

import Foundation

let catalogNames = [ "Hats", "Coats", "Trousers" ]

let matchingTerms = catalogNames.filter {
  $0.rangeOfString(self.txtField.text!, options: .CaseInsensitiveSearch).location != NSNotFound
}

答案 5 :(得分:2)

借助String扩展,您可以使用纯Swift解决方案(无需导入Foundation)。我没有检查速度,但它不应该更糟糕的基础相当。

extension String {
    func contains(string: String)->Bool {
        guard !self.isEmpty else {
            return false
        }
        var s = self.characters.map{ $0 }
        let c = string.characters.map{ $0 }
        repeat {
            if s.startsWith(c){
                return true
            } else {
                s.removeFirst()
            }
        } while s.count > c.count - 1
        return false
    }
}

let arr = ["Hello","Bye","Halo"]
let filtered = arr.filter { $0.contains("lo") }

print(filtered) // ["Hello", "Halo"]

"a".contains("alphabet") // false
"alphabet".contains("")  // true

答案 6 :(得分:0)

Swift 5
考虑下面的例子。从数组 1 中过滤(不区分大小写)数据并用该数据填充第二个数组

let data = ["Apple", "Oranges", "Banana", "Grapes"]
var filteredData = [String]()

func filterText(_ text: String?) {
    guard let text = text else {return}
    
    filteredData.removeAll()
    for element in data {
        if element.lowercased().starts(with: text.lowercased()){
            filteredData.append(element)
        }
    }
}