[英]Swift - How to get index of Dictionary element from value?
I am using a Array of Dictionary (Swift 4.1) to store the value of language name and language code: 我正在使用字典数组(Swift 4.1)来存储语言名称和语言代码的值:
var voiceLanguagesList: [Dictionary<String, String>] = []
I am appending array of dictionary by this method: 我通过这种方法追加字典数组:
for voice in AVSpeechSynthesisVoice.speechVoices() {
let voiceLanguageCode = (voice as AVSpeechSynthesisVoice).language
if let languageName = Locale.current.localizedString(forLanguageCode: voiceLanguageCode) {
let dictionary = [ControllerConstants.ChooseLanguage.languageName: languageName, ControllerConstants.ChooseLanguage.languageCode: voiceLanguageCode]
voiceLanguagesList.append(dictionary)
}
}
Now let say I have stored value of the element in userDefaults: 现在说我已经将元素的值存储在userDefaults中:
let languageName = UserDefaults.standard.object(forKey: ControllerConstants.UserDefaultsKeys.languageName) as? String
let languageCode = UserDefaults.standard.object(forKey: ControllerConstants.UserDefaultsKeys.languageCode) as? String
I want to get the index of the dictionary where the value is languageName
and languageCode
. 我想获取值是
languageName
和languageCode
的字典的索引 。 I gone through other answers but didn't find any good solution. 我经历了其他答案,但没有找到任何好的解决方案。
SourceCode: https://github.com/imjog/susi_iOS/tree/voice 源代码: https : //github.com/imjog/susi_iOS/tree/voice
File Link: https://github.com/imjog/susi_iOS/blob/voice/Susi/Controllers/LanguagePickerController/LanguagePickerController.swift 文件链接: https : //github.com/imjog/susi_iOS/blob/voice/Susi/Controllers/LanguagePickerController/LanguagePickerController.swift
Dictionaries are unordered. 字典是无序的。 They do not have an index.
他们没有索引。 Dictionaries have keys, which are some hashable value.
字典具有键,它们是一些可哈希的值。
All the keys in a dictionary are unique, but not all the values are. 词典中的所有键都是唯一的,但并非所有值都是唯一的。
You can have a Dictionary of type [String:Int]
with the values 您可以使用类型为
[String:Int]
的Dictionary,并将其值
["a": 1, "b": 1, "c": 1]
What is the key for value 1 in that case? 在这种情况下,值1的关键是什么? Would any key that contains that value be ok?
包含该值的任何键都可以吗? In that case you could loop through the key/value pairs until you find a matching value and return that key, but there's no such thing as the first matching value because, as mentioned, dictionaries are unordered.
在那种情况下,您可以遍历键/值对,直到找到匹配的值并返回该键,但是没有第一个匹配的值,因为如上所述,字典是无序的。
I don't see the need of using dictionary here. 我认为这里不需要使用字典。 You can simply create a new type Language and do the search as below.
您可以简单地创建一种新的语言类型,然后按以下方式进行搜索。
struct Language: Equatable {
var code: String
var name: String
}
var languages = [Language]()
languages.append(Language(code: "1", name: "English"))
languages.append(Language(code: "2", name: "Hindi"))
let languageToSearch = Language(code: "2", name: "Hindi")
print(languages.index(of: languageToSearch) ?? "Not found")
As have been already said by others, I dont see the point of using an array of dictionaries as a model for your table view... however, if I understood your question, could this help? 正如其他人已经说过的那样,我不认为使用字典数组作为表视图模型的意义……但是,如果我理解了您的问题,这会有所帮助吗? Greetings
问候
var testDictArray: [Dictionary<String, String>] = [] // Just a test, an array of dictionaries
// Filling the dictionary with example data
testDictArray.append(
["A0":"a0",
"B0":"b0",
"C0":"c0"]
)
testDictArray.append(
["A1":"a1",
"B1":"b1",
"C1":"c1",
"D1":"d1"]
)
testDictArray.append(
["A2":"a2",
"B2":"b2"]
)
// The example values you want to find
let upperCase = "B2"
let lowerCase = "b2"
// Some loops...
var foundedIndex: Int? = nil
for index in 0..<testDictArray.count {
for (key, value) in testDictArray[index] {
if (key, value) == (upperCase, lowerCase) {
foundedIndex = index
break
}
}
if foundedIndex != nil {
break
}
}
// Printing result
if let myIndex = foundedIndex {
print("The index is \(myIndex)") // The example returns 2
} else {
print("No index found :(")
}
Dictionary is key-value paired
字典是键值对
If you want to get index of Dictionary element from value. 如果要从值获取Dictionary元素的索引。
You can try with array of tuple like below: 您可以尝试使用元组数组,如下所示:
let dict = [("key0", "value0"), ("key1", "value1")]
let index = dict.index { $1 == "value1" } ?? 0
print(index) // 1
Hope it is useful! 希望它有用!
I have an array of dictionaries where dictionary is of type <String,Any>
. 我有一个字典数组,其中字典的类型为
<String,Any>
。
After some research and hit and trial, I have found something which works for me. 经过一番研究和尝试之后,我发现了一些对我有用的东西。
if let index = yourArray?.firstIndex(
where: {
($0 as AnyObject)["Title"] as? String == NSLocalizedString("New Location", comment: "")
}
)
{
print(index)
//your operations here
}
PS - ($0 as AnyObject)["Title"] as? PS-($ 0为AnyObject)[“标题”]为? String is the text you wish to find..
字符串是您要查找的文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.