简体   繁体   中英

How to get an array which is the value of a Dictionary key in Swift?

My data is structured like this:

var songs = [String: [Song]]()

It is a dictionary of which the keys are strings and the values are arrays. I'm basically sorting songs by name alphabetically so I can distribute them by sections in my TableView.

I'd like to get the song name like this:

var sectionTitle = self.tableView(tableView, titleForHeaderInSection: indexPath.section) as String! var songName = songs[sectionTitle][indexPath.row] as String var sectionTitle = self.tableView(tableView, titleForHeaderInSection: indexPath.section) as String! var songName = songs[sectionTitle][indexPath.row] as String (The error is in this line)

But XCode throws an error and says that String is not convertible to DictinoaryIndex<String, [(Song)]>

The problem you are having is that Swift dictionary lookups by key return an optional – the reason being, the key might not be in the dictionary.

So you need to unwrap the optional in some fashion (that is, check the key was valid).

Try the following:

if let songName = songs[sectionTitle]?[indexPath.row] {
    // use songName
}
else {
    // possibly log an error
}

You're also a little exposed to the risk of an index out of bound error as well, which (if you're using Xcode 6.3) you can guard against like this:

if let songList = songs[sectionTitle] where songList.count < indexPath.row {
    let song = songList[indexPathrow]

}

Generally speaking, you should spend some time learning about optionals and techniques for unwrapping them, instead of resorting to as and ! so much – your app will crash randomly if you find yourself unwrapping nils by accident like this.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM