将NSDictionary中的特定元素添加到NSArray中



所以我有这个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密钥中所有StringArray,可以使用NSDictionaryallKeys属性和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]

然而,我认为没有充分的理由使用Strings中的Arrays作为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作为键

最新更新