2016-11-24 23 views
-1

我有一本字典使用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 
} 
+3

請檢查日在你的indexPath實際上是一個'NSIndexPath'。 Coz Swift 3在表委託方法中使用'IndexPath'(而不是'NSIndexPath')。如果是這樣,你可以使用'if let size = cachedCellSizes [indexPath as! NSIndexPath]'或將字典鍵更改爲'IndexPath' – RJE

回答

1
fileprivate var cachedCellSizes: [NSIndexPath: CGSize] = [:] 

if let size = cachedCellSizes[indexPath as NSIndexPath] { 
    print(indexPath) 
} 

OR

fileprivate var cachedCellSizes: [IndexPath: CGSize] = [:] 

if let size = cachedCellSizes[indexPath] { 
    print(indexPath) 
} 
+1

第一個解決了我的問題,謝謝! – HoangNA

+1

第二種方法更可取。 – Alexander

+0

@AlexanderMomchliov是對的,因爲你使用的是Swift 3,所以第二個是可取的。 – Callam

相關問題