-1

I have a dictionary used NSIndexPath as key. It works fine with Swift 2 but I can't find a solution to make it work with Swift 3. I don't want to use String as a key so please don't suggest it.

// init
fileprivate var cachedCellSizes: [NSIndexPath: CGSize] = [:] 

// get value 
if let size = cachedCellSizes[indexPath] {
    return size
}

Compiler error:

Ambiguous reference to member 'subscript'

Some solution I had tried but doesn't work:

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
}
HoangNA
  • 163
  • 1
  • 12
  • 3
    Please check that your indexPath is actually a `NSIndexPath`. Coz Swift 3 uses `IndexPath` (not `NSIndexPath`) in table delegate methods. If so you can use `if let size = cachedCellSizes[indexPath as! NSIndexPath]` or change dictionary key as `IndexPath` – RJE Nov 24 '16 at 02:31

1 Answers1

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)
}
Callam
  • 11,409
  • 2
  • 34
  • 32