【问题标题】:Swift: Getting dictionary value if I know the key斯威夫特:如果我知道关键就获取字典值
【发布时间】:2016-03-02 00:11:34
【问题描述】:

这应该是超级基本的,但我还是遇到了错误。

Cannot subscript a value of type 'Dictionary<String, AnyObject>' with an index of type 'String'

这是我的代码:

func createComments(attributes: [[String: AnyObject]], votes: [String: AnyObject], sid: Int) -> [Comment] {
    var comments: [Comment] = [Comment]()

    for commentAttributes in attributes {
        let comment = Comment()
        comment.commentId = commentAttributes["id"]
        comments.append(comment)
    }  

    return comments
}

我在这一行收到错误:

comment.commentId = commentAttributes["id"]

据我所知,commentAttributes 应该是一个字典,其键为字符串,值为 AnyObject。除了使用字符串下标之外,我不确定如何使用字符串键访问字典的值。我在这里错过了什么?

【问题讨论】:

  • Comment的定义在哪里?它有成员commentId吗?

标签: swift dictionary subscript


【解决方案1】:

尝试使用if let 并将其转换为正确的类型。

for commentAttributes in attributes {
        let comment = Comment()
        if let id = commentAttributes["id"] as? Int {
           comment.commentId = id
        }
        comments.append(comment)
} 

【讨论】:

    【解决方案2】:

    当然,只要我提出问题,我就会找到答案:

    Cannot subscript a value of type '[String : AnyObject]' with an index of type 'String'

    我需要对commentAttributes["id"] 的值进行类型转换,使其与comment.commentId 的类型相匹配

    comment.commentId = commentAttributes["id"] as! Int

    【讨论】:

    • 感谢您发布参考。确实是一个误导性的错误消息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多