2016-03-01 117 views
1

这应该是超级基本的,但是我得到一个错误。Swift:如果我知道密钥,就可以获取字典值

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值的字典。我不知道除了通过使用字符串到下标以外,还有什么方法可以使用String键访问Dictionary的值。我在这里错过了什么?

+0

“Comment”的定义在哪里?它有一个''commentId''成员吗? – formal

回答

0

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

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