0

我正在使用 swift 1 参加在线课程。这些代码在 1 处没问题,但在 2 处显示运行时错误。

MusicLibrary.swift

let library = [
    [
        "title": "Rise and Shine",
        "description": "Get your morning going by singing along to these classic tracks as you hit the shower bright and early!",
        "icon": "coffee.pdf",
        "largeIcon": "coffee_large.pdf",
        "backgroundColor": ["red": 255, "green": 204, "blue": 51, "alpha": 1.0],
        "artists": ["American Authors", "Vacationer", "Matt and Kim", "MGMT", "Echosmith", "Tokyo Police Club", "La Femme"]
    ]

播放列表.swift

    init(index: Int) {
    let musicLibrary = MusicLibrary().library
    let playlistDictionary = musicLibrary[index]

    title = playlistDictionary["title"] as String!
    description = playlistDictionary["description"] as String!

    let iconName = playlistDictionary["icon"] as String!
    icon = UIImage(named: iconName!)

    let largeIconName = playlistDictionary["largeIcon"] as String!
    largeIcon = UIImage(named: largeIconName!)

    artists += playlistDictionary["artist"] as [String]
}
4

3 回答 3

0

我不知道为什么你得到“艺术家”(字符串)而不是“艺术家”(数组)。无论如何,使用您的代码,可以像这样修复:

   if objects.objectForKey("artist") != nil
   {
      let artist = playlistDictionary("artist") as [String]
       artists += artist
   }
于 2015-11-16T05:02:57.347 回答
0

什么错误?

在 swift 2 中,您必须编码:

if let _title = playlistDictionary["title"] as? String{
   self.title = _title
}

或者如果 playlistDictionary 是可选的:

if let _title = playlistDictionary?["title"] as? String{
   self.title = _title
}
于 2015-11-16T05:05:13.110 回答
0
let library:[Dictionary<String,Any>] = [
    [
        "title": "Rise and Shine",
        "description": "Get your morning going by singing along to these classic tracks as you hit the shower bright and early!",
        "icon": "coffee.pdf",
        "largeIcon": "coffee_large.pdf",
        "backgroundColor": ["red": 255, "green": 204, "blue": 51, "alpha": 1.0],
        "artists": ["_American Authors", "_Vacationer", "_Matt and Kim", "_MGMT", "_Echosmith", "_Tokyo Police Club", "_La Femme"]
    ],
    [
        "title": "Rise and Shine",
        "description": "Get your morning going by singing along to these classic tracks as you hit the shower bright and early!",
        "icon": "coffee.pdf",
        "largeIcon": "coffee_large.pdf",
        "backgroundColor": ["red": 255, "green": 204, "blue": 51, "alpha": 1.0],
        "artists": ["American Authors", "Vacationer", "Matt and Kim", "MGMT", "Echosmith", "Tokyo Police Club", "La Femme"]
    ]
]


var artists: [String] = []
library.forEach { (dict) -> () in
    if let arr = dict["artists"] as? [String] {
        artists += arr
    }
}
print(artists)
/*
["_American Authors", "_Vacationer", "_Matt and Kim", "_MGMT", "_Echosmith", "_Tokyo Police Club", "_La Femme", "American Authors", "Vacationer", "Matt and Kim", "MGMT", "Echosmith", "Tokyo Police Club", "La Femme"]

*/

如果您的图书馆是 [NSDictionary] 它仍然以相同的方式工作

于 2015-11-16T19:31:01.963 回答