简体   繁体   中英

How to search for a String containing certain Characters in a Set?

How can I search a Set to get the result below?

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

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

You can filter both sets and arrays with

filter(setOrArray, predicate)

the result is an array in either case. Whether all characters of a given set are contained in a string can be determined with

searchCharacters.isSubsetOf(string)

Together:

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]

This works if brands is an array or a set of String .

Remark: You should not define a literal array with 68k elements in the Swift source code. Better use a resource file (a simple text file or a property list) and load the array from there on runtime.

This will return an array from a set with strings containing letters from another set:

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)})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM