0

我试图将 NSMutableDictionary 的所有键值作为字符串数组。我正在使用它myNSMutableDictionary.allkeys来将值作为数组获取,但我找不到解包键值的方法。

这是我到目前为止所尝试的:

for (key, _) in NSMutableDictionary {
        println("THIS IS MY NEW KEY\(key)")
    }

我试过这个

var myArray:NSArray =  myNSMutableDictionary.allKeys
var string:NSString? = uniqueIDArray[0] as? NSString
println("This is unwraped value\(string!)")

和这个

var myArray:Array =  myNSMutableDictionary.allKeys
println("This is unwraped value\(myArray[0])")

我不断获得价值,Optional("kMSZgoTmiX")而不是kMSZgoTmiX我需要的关键价值

谢谢你的帮助!

4

2 回答 2

1

所以你有一个字典,其中的值是字符串(假设是字符串,键是字符串):

var dictionaryOfStringValues : [String:String] = /* your dictionary */

你想迭代内容:

for (key, val) in dictionaryOfStringValues {
  // use key and val
}

如果您只想以一种可以轻松迭代的方式获取值:

var theValues = dictionaryOfStringValues.values

如果您坚持认为theValuesArray

   var theValuesAsAnArray = Array(dictionaryOfStringValues.values)

如果你从 NSMutableDictionary 开始,那么在它第一次将你的 Swift 代码输入到 Swift 字典的地方将它转换。使用as变体来做到这一点。在那之后,纯斯威夫特。

像这样:

  7> for (key, value) in ["a":1, "b":2] { 
  8.     println (key) 
  9.     println (value) 
 10. }    
b
2
a
1
于 2015-03-25T01:48:20.717 回答
0
let myNSMutableDictionary = NSMutableDictionary()

myNSMutableDictionary["myKey1"] = 5
myNSMutableDictionary["myKey2"] = 10
myNSMutableDictionary["myKey3"] = 15

let myKeysArrayUnsorted =  myNSMutableDictionary.allKeys as [String]
let myValuesArrayUnsorted =  myNSMutableDictionary.allValues as [Int]

let keyString = myKeysArrayUnsorted[0]  // "myKey2"
let keyValue  = myNSMutableDictionary[keyString] as Int // 10

println("This is my first unsorted key \(keyString) = \(keyValue)")

let myKeysArraySorted =  (myNSMutableDictionary.allKeys as [String]).sorted(<)

for key in myKeysArraySorted {
    println(myNSMutableDictionary[key]!)  // 5 10 15
}
于 2015-03-25T03:01:03.037 回答