从字典的NSMutableArray获取字典

时间:2016-09-20 16:06:06

标签: ios swift nsmutablearray nsdictionary

我正试图从NSMutableDictionary获得NSMutableArray

我以这种方式设置我的数组:

let test : NSMutableDictionary = NSMutableDictionary()
    test.setValue("Monday", forKey: "day")
    test.setValue("7PM - 8PM", forKey: "hour")

    self.availabilityArray.add(test)

    let test1 : NSMutableDictionary = NSMutableDictionary()
    test1.setValue("Saturday", forKey: "day")
    test1.setValue("8PM - 10PM", forKey: "hour")
    self.availabilityArray.add(test1)

    let test2 : NSMutableDictionary = NSMutableDictionary()
    test2.setValue("Sunday", forKey: "day")
    test2.setValue("2PM - 8PM", forKey: "hour")
    self.availabilityArray.add(test2)

在另一种方法中,我尝试获取“day”和“hour”值以将其设置为UILabel

我试过这样做:

let dico = self.availabilityArray[i] //i being the index of a loop, not important here
self.dayNameLabel.text = (dico as AnyObject).object(forKey:"day") // This line does not work, I want to do something like that.

那么如何才能将NSMutableArray的内容作为NSDictionary的精确索引获取?

感谢。

2 个答案:

答案 0 :(得分:0)

感谢Larme我找到了解决方案,我更换了

self.dayNameLabel.text = (dico as AnyObject).object(forKey:"day")

使用

self.dayNameLabel.text = (dico as! NSMutableDictionary).object(forKey:"day") as! String?

答案 1 :(得分:0)

你应该使用swift 2(或3)对象。

声明你的数组:

var availabilityArray: [[String: String]] = []

然后创建你的词典:

var test: [String: String] = [:]
test["day"] = "Monday"
test["hour"] = "7PM - 8PM"
var test1: [String: String] = [:]
test1["day"] = "Saturday"
test1["hour"] = "8PM - 10PM"
var test2: [String: String] = [:]
test2["day"] = "Sunday"
test2["hour"] = "2PM - 8PM"

将它们添加到数组中:

self.availabilityArray.append(test)
self.availabilityArray.append(test1)
self.availabilityArray.append(test2)

最后访问对象:

let dico = self.availabilityArray[0]
self.dayNameLabel.text = dico["day"]

dico [“day”]是可选的,因此请使用dico["day"]!或使用真正的展开if let