数组 – 从Swift中的数组转换为正则

前端之家收集整理的这篇文章主要介绍了数组 – 从Swift中的数组转换为正则前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个协议称为复合.

该协议有一个数组复合:[Composite]

我也有一个泛型子类GenericSubclass< T>:复合

当迭代数组时,最好我可以想出这样:

  1. for item in composites {
  2. if let item = item as? GenericSubclass<A> {
  3. let sc = SomeOtherClass<A>
  4. } else if let item = item as? GenericSubclass<B> {
  5. let sc = SomeOtherClass<B>
  6. } //and so on...
  7. }

有没有办法得到一个GenericSubclass,而不指定Generic?在我的用例中,我绝对不需要知道T.我只需要实例化具有相同泛型类型的另一个类.

任何帮助深表感谢.

目前还不清楚您使用所选择的“通用”(双关语)类名称来完成什么.我不认为有办法直接完成你想要的.即你不能把它当作一个通用的T,因为编译器需要一些方法来确定什么T在运行时使用.

但是,解决问题的一个方法是将API提升到Composite协议中:

  1. protocol Composite {
  2. var composites: [Composite] { get set }
  3. func otherClass() -> OtherProtocol
  4. }
  5.  
  6. protocol OtherProtocol { }
  7.  
  8. class GenericSubclass<T>: Composite {
  9. var composites: [Composite] = []
  10.  
  11. func otherClass() -> OtherProtocol {
  12. return SomeOtherClass<T>()
  13. }
  14. }
  15.  
  16. class SomeOtherClass<T>: OtherProtocol {}

所以现在当你实现你的循环,你可以依靠这个事实,因为每个元素都是一个Composite,你知道它必须通过otherClass()方法提供一个OtherProtocol的实例:

  1. var c = GenericSubclass<Int>()
  2. c.composites = [GenericSubclass<Double>(),GenericSubclass<Int>(),GenericSubclass<Character>()]
  3.  
  4. for item in c.composites {
  5. let sc = item.otherClass()
  6. print(sc)
  7. }

或者,如果只有GenericSubclass应该销售OtherProtocol,则可以使返回类型为可选,并为Composite的所有其他实现定义一个扩展名:

  1. protocol Composite {
  2. var composites: [Composite] { get set }
  3. func optionalClass() -> OtherProtocol?
  4. }
  5.  
  6. extension Composite {
  7. func optionalClass() -> OtherProtocol? {
  8. return nil
  9. }
  10. }

猜你在找的Swift相关文章