[英]How to get an array which is the value of a Dictionary key in Swift?
我的数据结构如下:
var songs = [String: [Song]]()
它是一个字典,其键是字符串,值是数组。 我基本上是按字母顺序对歌曲进行排序,因此可以在TableView中按部分分配它们。
我想要这样的歌曲名称:
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
(错误在此行)
但是XCode抛出错误,并说String is not convertible to DictinoaryIndex<String, [(Song)]>
您遇到的问题是,按键进行Swift字典查找会返回一个可选值-原因是,键可能不在字典中。
因此,您需要以某种方式打开可选组件(即,检查密钥是否有效)。
请尝试以下操作:
if let songName = songs[sectionTitle]?[indexPath.row] {
// use songName
}
else {
// possibly log an error
}
您也同样会面临索引超出范围错误的风险,如果您使用Xcode 6.3,则可以避免这种情况:
if let songList = songs[sectionTitle] where songList.count < indexPath.row {
let song = songList[indexPathrow]
}
一般来说,您应该花一些时间来学习有关可选内容和用于解开可选内容的技术的知识,而不是求助于as
和!
如此之多–如果您发现自己偶然松开钉子,您的应用程序将随机崩溃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.