搜索值数组以查找字典中的键

时间:2019-06-11 20:58:26

标签: arrays swift dictionary

我有一个字典,例如:

let dict = ["1" : ["one","une"],
            "2" : ["two","duex"]]

我正在使用以下代码搜索值以获取密钥。例如,如果我搜索“一个”,我将返回“ 1”。

let searchIndex = dict.firstIndex(where: { $0.value.contains("one") })

if let index = searchIndex {
  print("Return: \(dict[index].key)") // prints "1"    
} else {
  print("Could not find")
}

但是,这仅在我搜索完全匹配的字符串时才有效。我将如何仅通过搜索字符串的一部分来返回匹配的键。换句话说,如果我搜索“ on”,它不会返回“ 1”。

3 个答案:

答案 0 :(得分:1)

还有一个public void binaryToHexadecimal(String binary){ String hexadecimal; binary = leftPad(binary); System.out.println(convertBinaryToHexadecimal(binary)); } public String convertBinaryToHexadecimal(String binary){ String hexadecimal = ""; int sum = 0; int exp = 0; for (int i=0; i<binary.length(); i++){ exp = 3 - i%4; if((i%4)==3){ sum = sum + Integer.parseInt(binary.charAt(i)+"")*(int)(Math.pow(2,exp)); hexadecimal = hexadecimal + hexValues[sum]; sum = 0; } else { sum = sum + Integer.parseInt(binary.charAt(i)+"")*(int)(Math.pow(2,exp)); } } return hexadecimal; } public String leftPad(String binary){ int paddingCount = 0; if ((binary.length()%4)>0) paddingCount = 4-binary.length()%4; while(paddingCount>0) { binary = "0" + binary; paddingCount--; } return binary; } API

contains(where:

答案 1 :(得分:1)

也许不是最短的解决方案,但似乎可以正常工作

var foundKey: String?
dict.contains(where: { key, value in
   if value.contains(where: {$0.contains("on") }) {
       foundKey = key
       return true
    }
    return false
})

if let key = foundKey {
    print("Return: \(key)") 
} else {
    print("Could not find")
}

处理多个可能的匹配项

var foundKeys = [String]()
dict.contains(where: { key, value in
    if value.contains(where: {$0.contains("o") }) {
        foundKeys.append(key)
    }
    return false
})

if foundKeys.count > 0 {
    print("Return: \(foundKeys)")
} else {
    print("Could not find")
}

答案 2 :(得分:1)

您可以这样操作:

let dict = ["1" : ["one","une"],
            "2" : ["two","deux"],
            "11": ["eleven, onze"]]

let searchText = "on"

let goodKeys = dict.keys.filter { key in
    dict[key]!.contains { word in
        return word.contains(searchText)
    }
}

print(goodKeys)     //["1", "11"]

为回答您的评论,以下是一种解决方案:

let searchText = "one une"
let components = searchText.components(separatedBy: " ")

let goodKeys = dict.keys.filter { key in
    dict[key]!.contains { word in
        return components.contains { component in
            word.contains(component)
        }
    }
}

print(goodKeys)     //["1"]