如何在可选的String数组中展开NSMutableDictionary.allkeys

时间:2015-03-25 01:13:02

标签: ios swift nsarray nsdictionary optional-variables

我试图将NSMutableDictionary的所有键值作为String Array。我使用此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,这是我需要的关键值

感谢您的帮助!

2 个答案:

答案 0 :(得分: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变体来执行此操作。在那之后,纯粹的Swift。

像这样:

  7> for (key, value) in ["a":1, "b":2] { 
  8.     println (key) 
  9.     println (value) 
 10. }    
b
2
a
1

答案 1 :(得分: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
}