简体   繁体   中英

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:

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? Or maybe someone knows, would Swift support not concrete generics in future? Because as seen in Kotlin, this is not something that can be done in programming languages

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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