所以我有这个NSDictionary itemsDict
(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)
这就是字典的结构:
{
(
News
) = {
a = "www.hello.co.uk";
b = "www.hello.com";
};
(
Sport
) = {
c = "www.hello.co.uk";
d = "www.hello.com";
};
}
从上面的字典中,我希望能够只使用-来填充NSArrayCCD_ 2元素。我试过这个和其他一些方法,但它们似乎都不管用。我的Swift技能没有那么先进,我希望这篇文章有意义。
Sections = itemsDict.allKeysForObject(<#anObject: AnyObject#>)
要获得Dictionary
密钥中所有String
的Array
,可以使用NSDictionary
的allKeys
属性和reduce
函数,如下所示:
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)
输出:
[News, Sport]
然而,我认为没有充分的理由使用String
s中的Array
s作为Dictionary
密钥。相反,我只会直接使用String
作为密钥,就像这样:
var itemsDict = [
"News":["a":"www.hello.co.uk","b":"www.hello.com"],
"Sport":["c":"www.hello.co.uk","d":"www.hello.com"],
]
在这种情况下,获得Dictionary
的密钥中的Array
就像一样简单
let keys = itemsDict.keys.array
注意:我在这里使用keys
属性,前面使用allKeys
属性,因为这是本机Swift Dictionary
,而前面的代码是NSDictionary
,因为它使用NSArray
s作为键