获取 Swift 中 Dictionary 的值 3 哪个键不是字符串
Get value of Dictionary in Swift 3 which key isn't a String
我有一个使用 NSIndexPath 作为键的字典。它适用于 Swift 2,但我找不到使它适用于 Swift 3 的解决方案。我不想使用 String 作为键,所以请不要建议。
// 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
}
fileprivate var cachedCellSizes: [NSIndexPath: CGSize] = [:]
if let size = cachedCellSizes[indexPath as NSIndexPath] {
print(indexPath)
}
或
fileprivate var cachedCellSizes: [IndexPath: CGSize] = [:]
if let size = cachedCellSizes[indexPath] {
print(indexPath)
}
我有一个使用 NSIndexPath 作为键的字典。它适用于 Swift 2,但我找不到使它适用于 Swift 3 的解决方案。我不想使用 String 作为键,所以请不要建议。
// 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
}
fileprivate var cachedCellSizes: [NSIndexPath: CGSize] = [:]
if let size = cachedCellSizes[indexPath as NSIndexPath] {
print(indexPath)
}
或
fileprivate var cachedCellSizes: [IndexPath: CGSize] = [:]
if let size = cachedCellSizes[indexPath] {
print(indexPath)
}