如何搜索包含集合中某些字符的字符串?

时间:2015-05-24 17:39:32

标签: ios swift search set

如何搜索Set以获得以下结果?

let brands: Set = ["apple", "microsoft", "hp", "lenovo", "asus", "qualcomm", "intel", "kingston"]

findValueinSet(brands, withCharacters: "a", "u") // returns "asus"

2 个答案:

答案 0 :(得分:2)

您可以使用

过滤集和数组
filter(setOrArray, predicate)

结果是两种情况下的数组。是否所有人物 一个给定的集合包含在一个字符串中,可以用

确定
searchCharacters.isSubsetOf(string)

合:

let brands: Set<String> = ["apple", "microsoft", "hp", "lenovo", "asus", "qualcomm", "intel", "kingston"]
let searchCharacters = Set("au")

let filtered = filter(brands) { searchCharacters.isSubsetOf($0) }
println(filtered) // [qualcomm, asus]

如果brands是一个数组或一组String

,则此方法有效

备注:您不应该定义具有68k元素的文字数组 在Swift源代码中。更好地使用资源文件(简单的文本 文件或属性列表)并在运行时从那里加载数组。

答案 1 :(得分:0)

这将从一个集合返回一个数组,其中包含来自另一个集合的字母:

let brands: Set<String> = ["apple", "microsoft", "hp", "lenovo", "asus", "qualcomm", "intel", "kingston"]
let filters: Set<Character> = ["a", "u"]

func predicate(item: String, filters:Set<Character>) -> Bool {
  for single in filters {
    if contains(item, single) {
      return true
    }
  }
  return false
}


let found = filter(brands, {predicate($0, filters)})