Swift:如果我知道密钥,则获取字典值
Swift: Getting dictionary value if I know the key
这应该是超级基本的,但我还是遇到了错误。
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 下标之外,我不确定如何使用 String 键访问 Dictionary 的值。我在这里错过了什么?
当然,一旦我提出问题,我就会找到答案:
我需要对 commentAttributes["id"] 的值进行类型转换,使其与 comment.commentId
的类型匹配
comment.commentId = commentAttributes["id"] as! Int
尝试使用 if let
并将其转换为正确的类型。
for commentAttributes in attributes {
let comment = Comment()
if let id = commentAttributes["id"] as? Int {
comment.commentId = id
}
comments.append(comment)
}
这应该是超级基本的,但我还是遇到了错误。
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 下标之外,我不确定如何使用 String 键访问 Dictionary 的值。我在这里错过了什么?
当然,一旦我提出问题,我就会找到答案:
我需要对 commentAttributes["id"] 的值进行类型转换,使其与 comment.commentId
的类型匹配comment.commentId = commentAttributes["id"] as! Int
尝试使用 if let
并将其转换为正确的类型。
for commentAttributes in attributes {
let comment = Comment()
if let id = commentAttributes["id"] as? Int {
comment.commentId = id
}
comments.append(comment)
}