I'm taking online course with swift 1. These code are alright at 1 but show runtime error at 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"]
]
Playlist.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]
}
I don't know why you get "artist"(String) instead of "artists"(Array). Anyway, with your code, can fix like this:
if objects.objectForKey("artist") != nil
{
let artist = playlistDictionary("artist") as [String]
artists += artist
}
what 's error?
in swift 2 you must code:
if let _title = playlistDictionary["title"] as? String{
self.title = _title
}
or if playlistDictionary is optional :
if let _title = playlistDictionary?["title"] as? String{
self.title = _title
}
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"]
*/
if your library is [NSDictionary] it still works the same way
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.