【问题标题】:Error: Cannot subscript a value of 'Dictionary with an index of type 'Int64'错误:无法为“Int64”类型索引的“字典”值下标
【发布时间】:2016-09-04 18:03:26
【问题描述】:
var dict = Dictionary<Int64, ExternalInfo>()

为上面的字典创建一个扩展,比如

extension Dictionary where Key: IntegerLiteralConvertible, Value: ExternalInfo {

    func contains(id: Int64) -> Bool {
        return self[id] != nil
        /* return self[3] != nil */ // No issue
    }

    mutating func remove(id: Int64) {
        removeValueForKey(id)
    }
}

这两个语句都会引发一些编译器级别的错误。需要做什么??

不能为索引为 'Dictionary 的值下标 输入“Int64”

【问题讨论】:

    标签: swift dictionary


    【解决方案1】:

    尝试使用SignedIntegerType而不是IntegerLiteralConvertible,这是不同整数类型之间更好的通用协议:

    extension Dictionary where Key: SignedIntegerType, Value: ExternalInfo {
    
        func contains(id: Int64) -> Bool {
            return self[Key(id)] != nil
        }
    
        mutating func remove(id: Int64) {
            removeValueForKey(Key(id))
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-11-29
      • 2018-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多