Reputation: 2690
So I have this NSDictionary itemsDict
(in Swift):
var itemsDict : NSDictionary = [:] // Dictionary
var Sections : NSArray = [] // Array
itemsDict = [
["News"]:["a":"www.hello.co.uk","b":"www.hello.com"],
["Sport"]:["c":"www.hello.co.uk","d":"www.hello.com"],
]
print (itemsDict)
This is how the structure of the dictionary looks like:
{
(
News
) = {
a = "www.hello.co.uk";
b = "www.hello.com";
};
(
Sport
) = {
c = "www.hello.co.uk";
d = "www.hello.com";
};
}
From the dictionary above I want to be able to populate an NSArray with only the -
[News,Sports]
elements.
I've tried this and a few other methods but they just don't seem to cut it. My Swift skills are not that advanced and I hope this post make sense.
Sections = itemsDict.allKeysForObject(<#anObject: AnyObject#>)
Upvotes: 0
Views: 2373
Reputation: 42325
To get an Array
of all String
s in your Dictionary
's keys, you can use the allKeys
property of NSDictionary
along with a reduce
function, like so:
var itemsDict = [
["News"]:["a":"www.hello.co.uk","b":"www.hello.com"],
["Sport"]:["c":"www.hello.co.uk","d":"www.hello.com"],
]
let keys = (itemsDict.allKeys as [[String]]).reduce([], combine: +)
println(keys)
Outputs:
[News, Sport]
However, I don't see a good reason to use Array
s of String
s as your Dictionary
keys. Instead, I'd just use String
s as keys directly, like so:
var itemsDict = [
"News":["a":"www.hello.co.uk","b":"www.hello.com"],
"Sport":["c":"www.hello.co.uk","d":"www.hello.com"],
]
In which case, getting an Array
of the Dictionary
's keys is as simple as:
let keys = itemsDict.keys.array
Note: I'm using the keys
property here and the allKeys
property earlier because this is a native Swift Dictionary
while the earlier code is an NSDictionary
due to its use of NSArray
s for keys.
Upvotes: 1