【问题标题】:How to use not concrete type for generic variable in swift?如何在swift中为泛型变量使用非具体类型?
【发布时间】:2018-03-29 13:30:25
【问题描述】:

正如我从互联网和 Xcode 中了解到的,你不能这样做:

protocol Foo {}

class Bar<T: Foo> {

}

class A {
    var some: Bar<Foo>! // this one
}

因为泛型变量的类型必须是具体的。如何绕过这个限制?最简单的方法好像是用另外一个协议,比如B,然后把Bar&lt;Foo&gt;改成B,然后所有继承自Bar的类都必须实现协议B,但是好像不太方便,所以也许还有其他方法?或者也许有人知道,Swift 将来会不支持具体的泛型吗?因为正如在 Kotlin 中看到的那样,这不是在编程语言中可以完成的事情

【问题讨论】:

  • 这可能对您的情况有用(类型擦除):natashatherobot.com/swift-type-erasure
  • 是的,它是,但仍然有点“hacky”。看起来它与我的解决方案几乎相同 - 使所有 Bar childs 符合 B 协议:)
  • 试图绕过这个约束没有多大意义。也许在你需要这个的地方举一个具体的例子。

标签: swift generics swift-protocols


【解决方案1】:

我有一个例子,假设你想用一种很好的方式实现注入。

class Injectable<T: ServiceProtocol> {
  let type: ServiceProtocol.Type { return T.self }
  var value: T!
}

然后使用类似的东西

class ViewModel {
   let serviceA = Injectable<AbstractNetworkService>()
}

class DependencyProvider {
   ...
   func injectDependencies(into object: AnyObject) {
      // Here you would use a Mirror of object, go through every Injectable,
      // and set their values.
   }
}

这很好,因为您可以为 AbstractNetworkService(一种协议)注册一个实际的类,但 Swift 不会让您这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多