久しぶりにswift触ったらなかなか解決出来なかったのでメモ。
コード
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
let array = Beat.sharedInstance.getAllPath()
cell.textLabel?.text = array[indexPath.row]["name"] //error
return cell
}
error内容
Cannot subscript a value of type '[String : AnyObject]' with an index of type 'String'
あれー、辞書型のアクセス方法ってこれで合ってるはずなのになぜ…と調べること数十分…
原因
cell.textLabel?.textの型がStringなのに、辞書型の値から取り出した値がAnyObjectだったからでした。
よくよく考えれば確かに、、となったのですが型がゆるい言語を最近触っていたせいかなかなか気づけなかったです。。
解決コード
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
let array = Beat.sharedInstance.getAllPath()
cell.textLabel?.text = array[indexPath.row]["name"] as? String
return cell
}
これでOKですね!
余談
今思うと使う時にいちいちキャストしなきゃいけないような構造ってあんまりよくない気がしました。
単純に辞書型で返すのでなくて、オブジェクトを1個作ってプロパティでnameとかを管理したほうが
使いやすいな。。