【问题标题】:Cannot subscript a value of type 'String' with an index of type 'String'无法使用“String”类型的索引为“String”类型的值下标
【发布时间】:2016-02-08 06:02:40
【问题描述】:

我想在 tableview 单元格上显示一些名称,该单元格存储在 postFromFriends 数组中,但是当我编写下面显示的这段代码时,它给我一个错误“无法使用类型索引下标 'String' 类型的值'String'" 在名称常量的声明中。如果有人可以提供帮助。谢谢

var postsFromFriends = [String]()

这是我用于附加名称的数组。

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! FriendsTaskTableViewCell

    if let name = postsFromFriends[indexPath.row]["name"] as? String {
        cell.name?.text = name
    }
    return cell
}

【问题讨论】:

  • 请包含postsFromFriends数组的定义
  • 我确实检查了我编辑的问题@SohilR.Memon
  • 你如何向其中添加数据?
  • postsFromFriends[indexPath.row] 显然会返回一个字符串。
  • 只需从 json 获取我的数据并附加到 postFromFriends @SohilR.Memon

标签: ios arrays string swift


【解决方案1】:

您已将postsFromFriends 声明为String 的数组,但听起来您想要一个字典数组:

var postsFromFriends = [[String:String]]()

【讨论】:

    【解决方案2】:

    从您的错误消息中假设postsFromFriendsStrings 的数组,那么postsFromFriends[indexPath.row] 返回一个String,然后您尝试使用["name"] 对其进行下标。您是否打算将您的 postsFromFriends 数组用于存储字典或某些具有可下标名称字段的自定义对象类型?

    【讨论】:

    • 我做了,创建了一个数组来将字典存储在我有名称对象的字典中。
    猜你喜欢
    • 2017-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    • 2020-02-08
    相关资源
    最近更新 更多