【发布时间】:2015-07-07 00:28:46
【问题描述】:
我想使用NSMutableDictionary key 作为数组中的索引。以下是我的尝试:
for (key, value) in item.attendeesImages(){
println("Key: \(key) value: \(value)")
if cell.attendeesImage.count > key as! Int {
cell.attendeesImage[key].image = value as? UIImage
cell.attendeesImage[key].clipsToBounds = true
cell.attendeesImage[key].layer.cornerRadius = cell.attendeesImage[key as! Int].frame.size.width/2
}
}
但是,当我尝试这样做时,我收到一条错误消息:
Could not find member 'image', 'clipsToBounds', and 'cornerRadius'
我很困惑,因为我最初将密钥存储为 Int,所以我尝试在 if 语句中取出类型转换,但出现错误提示“
Binary operator '>' cannot be applied to operands of type 'Int' and 'AnyObject'
我只是有点困惑,希望能得到一些帮助。谢谢!
【问题讨论】:
-
数组只能被 Int 索引,不能被任意键索引。
item.attendeesImages的键值是什么?您不能将 Ints 存储在 NSMutableDictionary 中,您必须存储对象,所以也许您存储了NSNumber实例,其值由 int 设置?但是,既然可以使用数组,为什么还要这样做呢? -
@Paulw11 键是简单的数字,如 0、1、2 等,值是 UIImages。我的目标是,当我遍历
attendeesImagesNSMutableDictionary时,我可以将每个键用作cell.attendeesImages中的索引 -
它们可以是数字,因为您不能将 int 等类型存储在
NSMutableDictionary中 - 它们必须是NSNumbers 或Strings "1","2","3 '。如果它是一个 swift 字典,那么您可以存储 Int,但您必须将键向下转换为 Int - 这就是为什么您会收到有关 AnyObject 的错误。如果您删除if语句及其相关代码,那么值是什么通过您的打印语句登录控制台? -
@Paulw11 如果我删除
if语句,我需要在设置image、clipToBounds和cornerRadius时将密钥转换为Ints。但是,这样做时,我的程序会中断,因为我收到一条错误消息fatal error: Array index out of range。我发现我正在尝试访问一个索引,根据这个问题,它可能超出cell.attendeesImage范围,这就是为什么我添加了if statement:stackoverflow.com/questions/27641761/…。还有其他建议吗? -
我建议删除 if 语句只是为了尝试了解密钥的类型。如果字典和数组正确关联在一起,那么您永远不应该得到超出范围的数组索引。正如我在之前的评论中所说,我不明白为什么要使用带有整数作为键的字典——这更简单地作为数组实现。你是如何构建这本词典的?
标签: ios swift key nsmutabledictionary