HoangNA HoangNA - 14 days ago 5
Swift Question

Get value of Dictionary in Swift 3 which key isn't a String

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
}

Answer
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)
}