【问题标题】:Get value of Dictionary in Swift 3 which key isn't a String在 Swift 3 中获取字典的值,哪个键不是字符串
【发布时间】:2016-11-24 02:23:58
【问题描述】:

我有一个使用 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
}

【问题讨论】:

  • 请检查您的 indexPath 实际上是 NSIndexPath。 Coz Swift 3 在表委托方法中使用IndexPath(不是NSIndexPath)。如果是这样,您可以使用if let size = cachedCellSizes[indexPath as! NSIndexPath] 或将字典键更改为IndexPath

标签: swift dictionary swift3 nsdictionary nsindexpath


【解决方案1】:
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)
}

【讨论】:

  • 第二种方法更可取。
  • @AlexanderMomchliov 是对的,第二个更可取,因为您使用的是 Swift 3。
猜你喜欢
  • 2017-03-27
  • 2016-08-20
  • 2011-12-20
  • 1970-01-01
  • 2013-07-02
  • 2018-06-25
  • 1970-01-01
  • 2019-06-26
  • 2016-12-16
相关资源
最近更新 更多