【问题标题】:Cant use NSMutableDictionary key as index in array?不能使用 NSMutableDictionary 键作为数组中的索引?
【发布时间】: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 语句,我需要在设置imageclipToBoundscornerRadius 时将密钥转换为Ints。但是,这样做时,我的程序会中断,因为我收到一条错误消息 fatal error: Array index out of range。我发现我正在尝试访问一个索引,根据这个问题,它可能超出cell.attendeesImage 范围,这就是为什么我添加了if statementstackoverflow.com/questions/27641761/…。还有其他建议吗?
  • 我建议删除 if 语句只是为了尝试了解密钥的类型。如果字典和数组正确关联在一起,那么您永远不应该得到超出范围的数组索引。正如我在之前的评论中所说,我不明白为什么要使用带有整数作为键的字典——这更简单地作为数组实现。你是如何构建这本词典的?

标签: ios swift key nsmutabledictionary


【解决方案1】:

数组没有像字典那样的键。例如:

    var anArray = ["A","B","C"]
    // anArray[0] == "A"
    // anArray[1] == "B"
    // anArray[2] == "C"
    var aDict = ["itemOne": "A", "itemTwo": "B","itemThree": "C"
    //  aDict["itemOne"] == "A"

当您使用 for in 循环时,您在 (array/dictionary) 中的 for 值将作为 AnyObject 传递,因为 swift 不知道数组或字典中的值将是什么。

此外,除非您正在处理一些不接受新的 swiftier Dictionary 数据类型的 NS 库,否则您应该使用 Dictionary 而不是旧的 NSDictionary。

Apple 有一些关于使用 For in Loops 迭代字典的优秀文档,以及一些使用 .keys 和 .values 修饰符的巧妙技巧。

https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-03
    • 2021-12-25
    • 2013-11-05
    • 1970-01-01
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多