【问题标题】:Use class as generic type parameter in a method在方法中使用类作为泛型类型参数
【发布时间】:2018-05-25 19:54:31
【问题描述】:

我正在使用以下通用方法返回子类

class SomeClass {

    var childInstance: ParentClass?

    func getClass<T: ParentClass>() -> T? {
        return childInstance as? T
    }

    func usage() {
        if let view: ChildTwo = self.getClass() {
            view.someMethodOfClassTwo()
        }
    }
}

是否可以将类作为泛型类型参数传递?所以用法将是没有 if 语句,像这样:

self.getClass(type: ChildTwo)?.someMethodOfClassTwo()

上面用到的父/子类如下:

class ParentClass { }
class ChildOne: ParentClass {
    func someMethodOfClassOne() { }
}
class ChildTwo: ParentClass {
    func someMethodOfClassTwo() { }
}

更新ParentClass 是一个类,由于某种原因,我无法使用协议或将其更改为协议。

【问题讨论】:

    标签: swift generics


    【解决方案1】:

    是的,你可以。但我很困惑你将如何使用它。

    您需要稍微修改getClass&lt;T: ParentClass&gt;() -&gt; T? 函数的签名。我也故意更改了函数的名称,因为在您实际获取子实例的位置命名为 getClass 是没有意义的。

    class SomeClass {
    
        var childInstance: ParentClass?
    
        func getChild<T: ParentClass>(type: T.Type) -> T? {
            return childInstance as? T
        }
    
        func usage() {
            if let child = self.getChild(type: ChildTwo.self) {
                child.someMethodOfClassTwo()
            }
        }
    }
    

    同样,您也可以在没有 if-let 绑定的情况下使用它。但是你必须处理optional chaining

    SomeClass().getChild(type: ChildTwo.self)?.someMethodOfClassTwo()
    

    这里将ParentClass 作为一个类,当您传递一个实际上没有多大意义的泛型类类型时,您会获得自动完成功能:


    编辑:

    如果您将设计稍微修改为ParentClass 以成为Parent 协议,那么Xcode 自动完成将建议您进行更有意义的签名。见:

    protocol Parent { }
    class ChildOne: Parent {
        func functionOfChildOne() { }
    }
    class ChildTwo: Parent {
        func functionOfChildTwo() { }
    }
    
    class SomeClass {
    
        var childInstance: Parent?
    
        func getChild<T: Parent>(type: T.Type) -> T? {
            return childInstance as? T
        }
    
        func usage() {
            if let child = self.getChild(type: ChildTwo.self) {
                child.functionOfChildTwo()
            }
        }
    }
    

    Xcode 自动补全建议你传递一个符合Parent 协议的类型

    【讨论】:

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