How to unwrap NSMutableDictionary.allkeys in optional String Array

333 Views Asked by At

I am trying to get all the key values of NSMutableDictionary as String Array. I am using this myNSMutableDictionary.allkeys to get the values as an Array but I cannot find a way to unwrap the key values.

This is what I have tried so far:

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

And I tried this

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

And this

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

I keep getting the value as Optional("kMSZgoTmiX") instead of kMSZgoTmiX which is the key value I need

Thank you for all your help!

2

There are 2 best solutions below

0
On

So you've got a dictionary with values that are strings (and keys that are something, assume String):

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

And you want to iterate over the contents:

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

If you just want the values in a way you can easily iterate over:

var theValues = dictionaryOfStringValues.values

If you insist that theValues be an Array:

   var theValuesAsAnArray = Array(dictionaryOfStringValues.values)

If you are starting with an NSMutableDictionary, then convert it at the point where it FIRST ENTERS your Swift code into a Swift Dictionary. Use an as variant to do that. After that, pure Swift.

Like this:

  7> for (key, value) in ["a":1, "b":2] { 
  8.     println (key) 
  9.     println (value) 
 10. }    
b
2
a
1
0
On
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
}