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

我有一个协议称为复合.

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

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

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

for item in composites {
    if let item = item as? GenericSubclass<A> {
        let sc = SomeOtherClass<A>
    } else if let item = item as? GenericSubclass<B> {
        let sc = SomeOtherClass<B>
    } //and so on...
}

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

任何帮助深表感谢.

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

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

protocol Composite {
    var composites: [Composite] { get set }
    func otherClass() -> OtherProtocol
}

protocol OtherProtocol { }

class GenericSubclass<T>: Composite {
    var composites: [Composite] = []

    func otherClass() -> OtherProtocol {
        return SomeOtherClass<T>()
    }
}

class SomeOtherClass<T>: OtherProtocol {}

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

var c = GenericSubclass<Int>()
c.composites = [GenericSubclass<Double>(),GenericSubclass<Int>(),GenericSubclass<Character>()]

for item in c.composites {
    let sc = item.otherClass()
    print(sc)
}

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

protocol Composite {
    var composites: [Composite] { get set }
    func optionalClass() -> OtherProtocol?
}

extension Composite {
    func optionalClass() -> OtherProtocol? {
        return nil
    }
}

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...