简体   繁体   English

如何从 Swift 的字典中获取特定索引处的键?

[英]How do I get the key at a specific index from a Dictionary in Swift?

I have a Dictionary in Swift and I would like to get a key at a specific index.我有一个 Swift Dictionary ,我想在特定索引处获取一个键。

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 ?为什么 ?

That's because keys returns LazyMapCollection<[Key : Value], Key> , which can't be subscripted with an Int .这是因为keys返回LazyMapCollection<[Key : Value], Key> ,它不能用Int下标。 One way to handle this is to advance the dictionary's startIndex by the integer that you wanted to subscript by, for example:处理此问题的一种方法是将字典的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.请记住,字典本质上是无序的,因此不要期望给定索引处的键始终相同。

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

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

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) { $0.0 < $1.0 }
println(sortedKeysArray)   // [(a, 456), (c, 123), (d, 45)]

var sortedValuesArray = sorted(dict) { $0.1 < $1.1 }
println(sortedValuesArray) // [(d, 45), (c, 123), (a, 456)]

then iterate.然后迭代。

for (index, entry) in enumerate(sortedKeysArray) {
    println(index)    // 0   1   2
    println(entry.0)  // a   c   d
    println(entry.1)  // 456 123 45
}

If you want to create an ordered dictionary, you should look into Generics.如果你想创建一个有序的字典,你应该看看泛型。

From https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/CollectionTypes.html :https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/CollectionTypes.html

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 airportCodes = [String](airports.keys) // airportCodes is ["TYO", "LHR"]   
let airportNames = [String](airports.values) // airportNames is ["Tokyo", "London Heathrow"]

SWIFT 3. Example for the first element SWIFT 3. 第一个元素的示例

let wordByLanguage = ["English": 5, "Spanish": 4, "Polish": 3, "Arabic": 2]

if let firstLang = wordByLanguage.first?.key {
    print(firstLang)  // English
}

In Swift 3 try to use this code to get Key-Value Pair (tuple) at given index:Swift 3 中尝试使用此代码在给定索引处获取键值对(元组):

extension Dictionary {
    subscript(i:Int) -> (key:Key,value:Value) {
        get {
            return self[index(startIndex, offsetBy: i)];
        }
    }
}

SWIFT 4快速 4


Slightly off-topic: But here is if you have an Array of Dictionaries ie: [ [String : String] ]有点跑题:但如果你有一个字典数组,即: [[String : String] ]

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

Here is an example, using Swift 1.2这是一个示例,使用 Swift 1.2

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

I was looking for something like a LinkedHashMap in Java.我正在寻找类似于 Java 中的 LinkedHashMap 的东西。 Neither Swift nor Objective-C have one if I'm not mistaken.如果我没记错的话,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. [[String: UIImage]]但后来我意识到使用Array(dict)[index].key从字典中获取密钥很古怪,所以我选择了元组。 Now my array looks like [(String, UIImage)] so I can retrieve it by tuple.0 .现在我的数组看起来像[(String, UIImage)]所以我可以通过tuple.0检索它。 No more converting it to an Array.不再将其转换为数组。 Just my 2 cents.只有我的 2 美分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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