我有一本字典使用NSIndexPath作爲鍵。它適用於Swift 2,但我找不到解決方案使其與Swift 3一起工作。我不想將String用作關鍵字,因此請不要提示它。獲取Swift 3中字典的值,其中鍵不是字符串
// 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'。 Coz Swift 3在表委託方法中使用'IndexPath'(而不是'NSIndexPath')。如果是這樣,你可以使用'if let size = cachedCellSizes [indexPath as! NSIndexPath]'或將字典鍵更改爲'IndexPath' – RJE