我正在从Obj-c转换到Swift,有时它可能会非常令人沮丧,因为我可以在几分钟内完成Obj-C中的简单任务。我知道这是学习过程的一部分,但同样是grrrr。
我构建了一个测试应用程序,用歌曲名称查询iTunes并返回所有结果。但对于我的生活,我似乎无法解析单个字典级别的回归。
我可以使用此代码深入到我认为我有一系列词典的级别:
if let dictData = dictJSON["Data"] as? [String:Any], let arrResults = dictData["results"] as? Array<Any> {
然后我可以像这样遍历那个数组:
for i in 1...arrResults.count {
或
for dictThisSong in arrResults {
在任何一种情况下我得到的结果如下:
{
artistId = 158038;
artistName = "Fleetwood Mac";
artistViewUrl = "https://itunes.apple.com/us/artist/fleetwood-mac/id158038?uo=4";
artworkUrl100 = "http://is2.mzstatic.com/image/thumb/Music/v4/8e/75/28/8e752885-66d0-737c-11ef-4c706672997e/source/100x100bb.jpg";
artworkUrl30 = "http://is2.mzstatic.com/image/thumb/Music/v4/8e/75/28/8e752885-66d0-737c-11ef-4c706672997e/source/30x30bb.jpg";
artworkUrl60 = "http://is2.mzstatic.com/image/thumb/Music/v4/8e/75/28/8e752885-66d0-737c-11ef-4c706672997e/source/60x60bb.jpg";
collectionCensoredName = Rumours;
collectionExplicitness = notExplicit;
collectionId = 594061854;
collectionName = Rumours;
collectionPrice = "10.99";
collectionViewUrl = "https://itunes.apple.com/us/album/the-chain/id594061854?i=594061861&uo=4";
country = USA;
currency = USD;
discCount = 1;
discNumber = 1;
isStreamable = 0;
kind = song;
previewUrl = "https://audio-ssl.itunes.apple.com/apple-assets-us-std-000001/Music/v4/04/1d/85/041d85eb-f1fe-2d47-1ec7-2540582cece7/mzaf_3322367551095292692.plus.aac.p.m4a?accessKey=1516884136_9174591730773045036_io%2Bc9w6hmWHjPZOpZEgG1nZm9Hm%2FInFnTM%2FT3k8%2BoQZZW2ymomMWeZ8jGkN4TfX85U5U4WRYpxPN8e2svlMmBLE8boGG4aya9izAo%2FIvIMOZ4qt6XPuQQc5JstA%2FmihUGdKsa1Nbov9joyxnTnm7UlpKY2ZsqomfNv4SsJGfDG3cCgxtBoAOKR7Pj42lDYQN1jnRVqusi4Cpf9fHOXb5uA%3D%3D";
primaryGenreName = Rock;
releaseDate = "1977-02-04T08:00:00Z";
trackCensoredName = "The Chain";
trackCount = 11;
trackExplicitness = notExplicit;
trackId = 594061861;
trackName = "The Chain";
trackNumber = 7;
trackPrice = "1.29";
trackTimeMillis = 270213;
trackViewUrl = "https://itunes.apple.com/us/album/the-chain/id594061854?i=594061861&uo=4";
wrapperType = track;
}
如果我做了一种检查,我会得到NSDictionary:
print(type(of: dictThisSong))
__NSDictionaryI
__NSDictionaryI
__NSDictionaryI
__NSDictionaryI
__NSDictionaryI
__NSDictionaryI
__NSDictionaryI...
但如果我尝试打印dictThisSong [“artistName”],我会得到一个类型“Any”没有下标成员错误。
所以,那么我想也许我必须转向NSDictionary,但这会引发错误:
无法将Array类型的值转换为NSDictionary,如果我尝试转换为Dictionary
,则相同所以在我看来,错误信息是说我正在尝试将数组转换为字典但是打印输出的类型说我已经在使用字典了。任何帮助,将不胜感激。
完整代码:
func parseJSONResults(dictJSON:Dictionary<String, Any>) {
if let dictData = dictJSON["Data"] as? [String:Any], let arrResults = dictData["results"] as? Array<Any> {
for dictThisSong in arrResults {
print(dictThisSong)
}
} else {
print(dictJSON)
}
}
答案 0 :(得分:1)
你正在与强大型系统作斗争。帮助编译器比编译器会帮助你。
[Any]
是一个 数组,我不知道它是什么 但你做知道那是一个字典数组,所以把它投到[[String:Any]]
if let dictData = dictJSON["Data"] as? [String:Any],
let arrResults = dictData["results"] as? [[String:Any]] { ...