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)
请记住,词典本质上是无序的,所以不要指望给定索引处的键始终是相同的.
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)
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)
如果要创建有序字典,则应查看泛型.
如果您需要使用带有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)
在Swift 3 中尝试使用此代码在给定索引处获取键值对(元组):
extension Dictionary {
subscript(i:Int) -> (key:Key,value:Value) {
get {
return self[index(startIndex, offsetBy: i)];
}
}
}
Run Code Online (Sandbox Code Playgroud)
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)