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

the*_*tic 103 dictionary ios swift

我有一个Dictionary在Swift中,我想获得一个特定索引的密钥.

var myDict : Dictionary<String,MyClass> = Dictionary<String,MyClass>()
Run Code Online (Sandbox Code Playgroud)

我知道我可以遍历密钥并记录它们

for key in myDict.keys{

    NSLog("key = \(key)")

}
Run Code Online (Sandbox Code Playgroud)

然而,奇怪的是,这样的事情是不可能的

var key : String = myDict.keys[0]
Run Code Online (Sandbox Code Playgroud)

为什么?

Mic*_*lum 176

那是因为keys返回LazyMapCollection<[Key : Value], Key>,无法使用Int进行下标.处理此问题的一种方法是startIndex通过您想要下标的整数来推进字典,例如:

let intIndex = 1 // where intIndex < myDictionary.count
let index = myDictionary.startIndex.advancedBy(intIndex) // index 1
myDictionary.keys[index]
Run Code Online (Sandbox Code Playgroud)

另一种可能的解决方案是使用keys输入初始化数组,然后可以在结果上使用整数下标:

let firstKey = Array(myDictionary.keys)[0] // or .first
Run Code Online (Sandbox Code Playgroud)

请记住,词典本质上是无序的,所以不要指望给定索引处的键始终是相同的.

  • 为了澄清Rob所说的内容,虽然它可能*似乎*每次都按键排序相同,但事实并非如此,只是一个实现细节.您很可能可以添加键"foo",内部表示将完全重新排序字典.字典是**无序的键值对的集合.因此,上面的答案是做出一些不成立的危险假设. (7认同)
  • 如果您需要特定顺序的密钥,请保留它们的数组.然后你可以使用它们像`myDict [keysArray [0]]`. (7认同)
  • 请记住,没有关于这将返回哪个键的承诺,但是关于返回的"view"类型的好注意.删除了我的答案,因为它实际上并不适用于这个问题. (5认同)
  • 可能更快的是'Array(myDict)[0] .0`因为它不会复制keys数组,并且不应该复制字典的内部结构,尽管它可能会. (3认同)

roy*_*roy 45

Swift 3:Array()这样做很有用.

获取密钥:

let index = 5 // Int Value
Array(myDict)[index].key
Run Code Online (Sandbox Code Playgroud)

获得价值:

Array(myDict)[index].value
Run Code Online (Sandbox Code Playgroud)


bzz*_*bzz 26

这是一个小型扩展,用于按索引访问字典中的键和值:

extension Dictionary {
    subscript(i: Int) -> (key: Key, value: Value) {
        return self[index(startIndex, offsetBy: i)]
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 'advance'API已在Swift 2.0中删除 - self [self.startIndex.advancedBy(i)] - (3认同)
  • @TomSawyer 字典没有排序。 (3认同)

Mat*_*aal 10

您可以遍历字典并使用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)
}
Run Code Online (Sandbox Code Playgroud)

如果你想先排序..

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)]
Run Code Online (Sandbox Code Playgroud)

然后迭代.

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

如果要创建有序字典,则应查看泛型.

  • @Max,这是旧的 Swift 语法。现在你可以使用:`dict.enumerated().forEach { (index, element) in ... }` (2认同)

Jac*_*ack 8

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

如果您需要使用带有Array实例的API的字典键或值,请使用keys或values属性初始化新数组:

let airportCodes = [String](airports.keys) // airportCodes is ["TYO", "LHR"]   
let airportNames = [String](airports.values) // airportNames is ["Tokyo", "London Heathrow"]
Run Code Online (Sandbox Code Playgroud)


Mic*_*bro 7

Swift 3 中尝试使用此代码在给定索引处获取键值对(元组):

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


Vla*_*iak 5

SWIFT 3.第一个元素的示例

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

if let firstLang = wordByLanguage.first?.key {
    print(firstLang)  // English
}
Run Code Online (Sandbox Code Playgroud)

  • 如果我想获得密钥是波兰语的索引怎么办? (2认同)