【问题标题】:Swift generics and subscript - value is not identical to KSwift 泛型和下标 - 值与 K 不同
【发布时间】:2014-10-02 23:28:38
【问题描述】:

我收到一个编译错误,因为编译器认为我的元组中的“键”与泛型数组的类型不同。知道为什么吗?

class MyClass <K: Hashable, V> {

   let keys = [K]()

   subscript(index: Int) -> (key: K, value: V) {
      set(newValue) {
         // also tried newValue.key!
         keys[index] = newValue.key
      }
   }
}

【问题讨论】:

  • 顺便说一句,为什么你在 setter 中有 return 语句?它也应该给你一个编译错误?
  • @Keenle 抱歉,我的问题打错了,实际代码是正确的

标签: generics swift subscript


【解决方案1】:

您正在尝试设置数组keys 的值,而它被声明为不可变数组。 keys 数组应声明为:

var keys = [K]() // var declaration makes it mutable

【讨论】:

  • 太棒了。使数组最终而不是使用 let
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-25
  • 2022-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多