简体   繁体   English

swift如何在通用变量中使用非具体类型?

[英]How to use not concrete type for generic variable in swift?

As I have learned from internet and Xcode you can't do something like this: 正如我从Internet和Xcode中学到的,您不能做这样的事情:

protocol Foo {}

class Bar<T: Foo> {

}

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

because types for generic variables must be concrete. 因为通用变量的类型必须是具体的。 How to bypass that restriction? 如何绕过该限制? The easiest way seems to use another protocol, for example B , then change Bar<Foo> to B , and then all the classes that inherits from Bar must implement protocol B , but it's seems not very convenient, so maybe another ways? 最简单的方法似乎是使用另一个协议,例如B ,然后将Bar<Foo>更改为B ,然后所有从Bar继承的类都必须实现协议B ,但这似乎不是很方便,所以也许还有其他方法吗? Or maybe someone knows, would Swift support not concrete generics in future? 也许有人知道,Swift将来会支持不具体的泛型吗? Because as seen in Kotlin, this is not something that can be done in programming languages 因为就像在Kotlin中看到的那样,这不是用编程语言可以完成的事情

I have an example, let say you want to implement Injection with a nice way. 我有一个例子,假设您想以一种不错的方式实现注入。

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

Then use something like 然后使用类似

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.
   }
}

That is nice because you can register an actual class for an AbstractNetworkService (a protocol), but Swift won't let you do that. 很好,因为您可以为AbstractNetworkService(协议)注册实际的类,但是Swift不允许您这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM