PatientC
PatientC

Reputation: 273

get Values from NSMutableDictionary in swift?

I have a stored NSMutableDictionary in NSUSerDefaluts and i have retrieve that successfully.

if var tempFeed: NSDictionary = NSUserDefaults.standardUserDefaults().dictionaryForKey("selectedFeeds") {
       println("selected Feed: \(tempFeed)")
        savedDictionary = tempFeed.mutableCopy() as NSMutableDictionary

The Question is How can i convert that MutableDictionary into an array/MuatableArray and iterate it so i can get the values of it.Here is the Dictionary. i want to get the values for all URL in that.

{
4 =     {
    URL = "myurl1";
};
5 =     {
    URL = "myurl3";
};
6 =     {
    URL = "myurl3";
};
}

I have tried number of options with failure. Thank you.

Upvotes: 1

Views: 672

Answers (3)

Airspeed Velocity
Airspeed Velocity

Reputation: 40965

If all you want to do is iterate over it, you don’t have to convert it to an array. You can do that directly:

for (key,value) in savedDictionary {
    println("\(key) = \(value)")
}

(if you’re not interested in the key at all, you can replace that variable name with _ to ignore it).

Alternatively, instead of making tempFeed of type NSDictionary, just leave it as the type dictionaryForKey returns, which is a Swift dictionary. This has a .values property, which is a lazy sequence of all the values in the dictionary. You can convert that to an array (so tempFeed.values.array) or perform operations on it directly (use it in for…in, map it such as tempFeeds.values.map { NSURL(string: toString($0)) } etc.)

Upvotes: 1

saurabh
saurabh

Reputation: 6775

If you want to add all the urls into an array, iterate over it and add append all values to some array.

for (_,urlDict) in savedDictionary {
  for(_,url) in urlDict {
    urlArr.append(url) // create empty urlArr before
  }
}

urlArr now contains all the urls (not ordered)

Upvotes: 1

Christian
Christian

Reputation: 22343

You can use .values.array on your dictionary to get the values unordered. as an array Then, you can just add your NSArray to your NSMutableArray.

var mutableArray:NSMutableArray = NSMutableArray(array: savedDictionary .values.array)

Upvotes: 1

Related Questions