我对swift很陌生,我以前用的是objective C编写代码,但是现在在swift的开发中,我面临着很多问题。现在我已经在project中导入了json文件

let file = Bundle.main.url(forResource: "test", withExtension: "json")

do {
    let data = try Data(contentsOf: file!)

    //let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary

    let json:NSArray = try (JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.mutableContainers) as? NSArray)!


    print(json[0])

} catch let error as NSError {
    print("Failed to load: \(error.localizedDescription)")
}

它的输出像
{
Correct = 1;
    EA = "50 Days  ";
    EB = "40 days";
    EC = "90 days";
    ED = "30  days";
}

我只需要用“EA”键访问内容。
在使用objective C之前,我曾经像
[[json objectAtIndex:0] objectForKey:@"EA"]

现在当我试图像
json[0].objectForKey("EA") as? String

上面写着
“Any”类型的值没有成员“objectForKey”
我该怎么办?

最佳答案

斯威夫特2

(json[0] as! NSDictionary).objectForKey("EA") as? String

Swift 3和4
(json[0] as! NSDictionary).object(forKey: "EA") as? String

关于arrays - 如何使用swift4中的键访问数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46661100/

10-10 11:26