LoginSignup
2

More than 3 years have passed since last update.

[小ネタ]辞書型から値を取ろうとした時に起きたエラー

Last updated at Posted at 2016-02-06

久しぶりに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とかを管理したほうが
使いやすいな。。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2