简体   繁体   English

如何在Swift中获取字典键值的数组?

[英]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. 我基本上是按字母顺序对歌曲进行排序,因此可以在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) var sectionTitle = self.tableView(tableView, titleForHeaderInSection: indexPath.section) as String! var songName = songs[sectionTitle][indexPath.row] as String (错误在此行)

But XCode throws an error and says that String is not convertible to DictinoaryIndex<String, [(Song)]> 但是XCode抛出错误,并说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. 您遇到的问题是,按键进行Swift字典查找会返回一个可选值-原因是,键可能不在字典中。

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: 您也同样会面临索引超出范围错误的风险,如果您使用Xcode 6.3,则可以避免这种情况:

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 ! 一般来说,您应该花一些时间来学习有关可选内容和用于解开可选内容的技术的知识,而不是求助于as! so much – your app will crash randomly if you find yourself unwrapping nils by accident like this. 如此之多–如果您发现自己偶然松开钉子,您的应用程序将随机崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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