2016-11-24 24 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

相关问题