ios 我如何从斯威夫特字典中的特定索引的关键?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24640990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the key at a specific index from a Dictionary in Swift?
提问by the_critic
I have a Dictionary
in Swift and I would like to get a key at a specific index.
我Dictionary
在 Swift 中有一个,我想在特定索引处获取一个键。
var myDict : Dictionary<String,MyClass> = Dictionary<String,MyClass>()
I know that I can iterate over the keys and log them
我知道我可以遍历键并记录它们
for key in myDict.keys{
NSLog("key = \(key)")
}
However, strangely enough, something like this is not possible
然而,奇怪的是,这样的事情是不可能的
var key : String = myDict.keys[0]
Why ?
为什么 ?
回答by Mick MacCallum
That's because keys
returns LazyMapCollection<[Key : Value], Key>
, which can't be subscripted with an Int
. One way to handle this is to advance the dictionary's startIndex
by the integer that you wanted to subscript by, for example:
这是因为keys
回报LazyMapCollection<[Key : Value], Key>
,这是不能用为下标Int
。处理此问题的一种方法是startIndex
通过您想要下标的整数来推进字典,例如:
let intIndex = 1 // where intIndex < myDictionary.count
let index = myDictionary.index(myDictionary.startIndex, offsetBy: intIndex)
myDictionary.keys[index]
Another possible solution would be to initialize an array with keys
as input, then you can use integer subscripts on the result:
另一种可能的解决方案是使用keys
作为输入初始化数组,然后您可以在结果上使用整数下标:
let firstKey = Array(myDictionary.keys)[0] // or .first
Remember, dictionaries are inherently unordered, so don't expect the key at a given index to always be the same.
请记住,字典本质上是无序的,因此不要期望给定索引处的键始终相同。
回答by roy
Swift 3 : Array()
can be useful to do this .
Swift 3:Array()
可以用于执行此操作。
Get Key :
获取密钥:
let index = 5 // Int Value
Array(myDict)[index].key
Get Value :
获取价值:
Array(myDict)[index].value
回答by bzz
Here is a small extension for accessing keys and values in dictionary by index:
这是通过索引访问字典中的键和值的小扩展:
extension Dictionary {
subscript(i: Int) -> (key: Key, value: Value) {
return self[index(startIndex, offsetBy: i)]
}
}
回答by Matthew Korporaal
You can iterate over a dictionary and grab an index with for-in and enumerate (like others have said, there is no guarantee it will come out ordered like below)
您可以遍历字典并使用 for-in 和 enumerate 获取索引(就像其他人所说的那样,不能保证它会按如下顺序排列)
let dict = ["c": 123, "d": 045, "a": 456]
for (index, entry) in enumerate(dict) {
println(index) // 0 1 2
println(entry) // (d, 45) (c, 123) (a, 456)
}
If you want to sort first..
如果你想先排序..
var sortedKeysArray = sorted(dict) { for (index, entry) in enumerate(sortedKeysArray) {
println(index) // 0 1 2
println(entry.0) // a c d
println(entry.1) // 456 123 45
}
.0 < .0 }
println(sortedKeysArray) // [(a, 456), (c, 123), (d, 45)]
var sortedValuesArray = sorted(dict) { let airportCodes = [String](airports.keys) // airportCodes is ["TYO", "LHR"]
let airportNames = [String](airports.values) // airportNames is ["Tokyo", "London Heathrow"]
.1 < .1 }
println(sortedValuesArray) // [(d, 45), (c, 123), (a, 456)]
then iterate.
然后迭代。
extension Dictionary {
subscript(i:Int) -> (key:Key,value:Value) {
get {
return self[index(startIndex, offsetBy: i)];
}
}
}
If you want to create an ordered dictionary, you should look into Generics.
如果你想创建一个有序的字典,你应该看看泛型。
回答by Hyman
If you need to use a dictionary's keys or values with an API that takes an Array instance, initialize a new array with the keys or values property:
如果您需要将字典的键或值与采用 Array 实例的 API 一起使用,请使用 keys 或 values 属性初始化一个新数组:
let wordByLanguage = ["English": 5, "Spanish": 4, "Polish": 3, "Arabic": 2]
if let firstLang = wordByLanguage.first?.key {
print(firstLang) // English
}
回答by Micha? Ziobro
In Swift 3try to use this code to get Key-Value Pair (tuple) at given index:
在Swift 3 中尝试使用此代码在给定索引处获取键值对(元组):
var person = ["name":"Sean", "gender":"male"]
person.keys.array[1] // "gender", get a dictionary key at specific index
person.values.array[1] // "male", get a dictionary value at specific index
回答by W?odzimierz Wo?niak
SWIFT 3. Example for the first element
SWIFT 3. 第一个元素的示例
var array_has_dictionary = [ // Start of array
// Dictionary 1
[
"name" : "xxxx",
"age" : "xxxx",
"last_name":"xxx"
],
// Dictionary 2
[
"name" : "yyy",
"age" : "yyy",
"last_name":"yyy"
],
] // end of array
cell.textLabel?.text = Array(array_has_dictionary[1])[1].key
// Output: age -> yyy
回答by Sean Chen
Here is an example, using Swift 1.2
这是一个示例,使用 Swift 1.2
##代码##回答by Suhaib
SWIFT 4
快速 4
Slightly off-topic:But here is if you have an Array of Dictionariesi.e:[ [String : String] ]
有点跑题:但如果你有一个 字典数组,即:[ [[String : String] ]
##代码##回答by newDeveloper
I was looking for something like a LinkedHashMap in Java. Neither Swift nor Objective-C have one if I'm not mistaken.
我正在寻找类似于 Java 中的 LinkedHashMap 的东西。如果我没记错的话,Swift 和 Objective-C 都没有。
My initial thought was to wrap my dictionary in an Array. [[String: UIImage]]
but then I realized that grabbing the key from the dictionary was wacky with Array(dict)[index].key
so I went with Tuples. Now my array looks like [(String, UIImage)]
so I can retrieve it by tuple.0
. No more converting it to an Array. Just my 2 cents.
我最初的想法是将我的字典包装在一个数组中。[[String: UIImage]]
但后来我意识到从字典中获取密钥很古怪,Array(dict)[index].key
所以我选择了元组。现在我的数组看起来像[(String, UIImage)]
这样我可以通过tuple.0
. 不再将其转换为数组。只有我的 2 美分。