不能使用NSMutableDictionary键作为数组中的索引?

时间:2015-07-07 00:28:47

标签: ios swift key nsmutabledictionary

我想在数组中使用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'

我只是有点困惑,并希望得到一些帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

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

    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循环时,(数组/字典)中的for值将作为AnyObject传递,因为swift不知道数组或字典中的值是什么。

除非你正在处理一些不接受新的更快的字典数据类型的NS库,否则你应该使用Dictionary而不是旧的NSDictionary。

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

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