获取Swift 3中字典的值,该键为';一根绳子
我有一本用XPath作为键的字典。它与Swift 2配合使用效果很好,但我无法找到一个解决方案使其与Swift 3配合使用。我不想使用字符串作为键,所以请不要建议它获取Swift 3中字典的值,该键为';一根绳子,swift,dictionary,swift3,nsdictionary,nsindexpath,Swift,Dictionary,Swift3,Nsdictionary,Nsindexpath,我有一本用XPath作为键的字典。它与Swift 2配合使用效果很好,但我无法找到一个解决方案使其与Swift 3配合使用。我不想使用字符串作为键,所以请不要建议它 // init fileprivate var cachedCellSizes: [NSIndexPath: CGSize] = [:] // get value if let size = cachedCellSizes[indexPath] { return size } 编译器错误: Ambiguous ref
// init
fileprivate var cachedCellSizes: [NSIndexPath: CGSize] = [:]
// get value
if let size = cachedCellSizes[indexPath] {
return size
}
编译器错误:
Ambiguous reference to member 'subscript'
我尝试过一些解决方案,但不起作用:
if let size:CGSize = cachedCellSizes[indexPath] as? CGSize {
return size
}
if let size:CGSize = cachedCellSizes[indexPath] as! CGSize {
return size
}
if let size:CGSize = cachedCellSizes["indexPath"] as CGSize {
return size
}
或
请检查您的indexPath实际上是
NSIndexPath
。因为Swift 3在表委托方法中使用indepath
(而不是nsindepath
)。如果是这样,您可以使用If let size=cachedCellSizes[indexPath as!NSIndexPath]
或将字典键更改为indexPath
第二种方法更可取。@AlexanderMomchliov是对的,第二种方法更可取,因为您使用的是Swift 3。
fileprivate var cachedCellSizes: [NSIndexPath: CGSize] = [:]
if let size = cachedCellSizes[indexPath as NSIndexPath] {
print(indexPath)
}
fileprivate var cachedCellSizes: [IndexPath: CGSize] = [:]
if let size = cachedCellSizes[indexPath] {
print(indexPath)
}