swift - 在 A 集合中存储符合关联类型的泛型

标签 swift

我正在尝试存储一个使用关联类型的泛型,但是在尝试创建一个应该符合我在类 A 顶部的泛型列表中描述的泛型类型的类型时,我得到了错误。

“无法使用类型为‘(B)’的参数列表调用‘append’”

我怎样才能正确地声明泛型以使这段代码工作?

class A<DataType: Any, AssociatedType: Runable> where 
AssociatedType.DataType == DataType {
  var array = Array<AssociatedType>()

  func addAssociatedValue(data: DataType) {
    array.append(B(data: data))
  }

  func runOnAll(with data: DataType) {
    for item in array {
      item.run(with: data)
    }
  }
}
class B<DataType>: Runable {
  init(data: DataType) { }
  func run(with: DataType) { }
}

protocol Runable {
  associatedtype DataType
  func run(with: DataType)
}

我也在使用 Swift 4.2,所以如果有一个使用较新 Swift 功能之一的解决方案也可以作为解决方案。

最佳答案

B 符合Runnable,是的,但是你不能将它放入一个应该存储AssociatedType 的数组中。因为 AssociatedType 的实际类型是由类的调用者决定的,而不是类本身。该类不能说“我希望 AssociatedType 始终为 B”。如果是这种情况,您不妨删除 AssociatedType 泛型参数并将其替换为 B。调用者可以将 AssociatedType 设为 FooBar 或任何符合 Runnable 的类型。现在你强制放入一个 B

我认为您应该重新考虑一下您的模型。问问自己是否真的想要 AssociatedType 作为通用参数。

您可以考虑为 Runnable 添加另一个要求:

init(data: DataType)

并将required添加到B的初始化器中。这样,您可以像这样编写 addAssociatedValue:

func addAssociatedValue(数据:数据类型){ array.append(关联类型(数据:数据))

关于swift - 在 A 集合中存储符合关联类型的泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51603860/

相关文章:

swift - Swift divide "/"运算符不工作还是我错过了什么?

linux - 如何在 Ubuntu linux 上启动和停止 Apple 基于 Swift 的生产服务器(我编写的程序)?

ios - 为银行账户信息 Stripe 创建 token

swift - 快速静态导入

ios - 解决 swift 和 xcode 6.4 beta 中的 Apple Mach-O 链接器错误

swift - 为什么我的 Swift 3 编码跑掉了?

ios - 打印通用结构集的地址以了解写时复制行为的含义的正确方法是什么?

ios - 显示用户在多段线中点击的标记

ios - 即使按钮没有在后台快速运行,如何禁用它?

swift - HealthKit – 如何获取分段距离(每公里)的运行事件?