在Swift中返回不同类类型的多态方法?

时间:2015-06-10 16:31:46

标签: swift polymorphism

我有一组异构对象类型(常见的超类)。每个元素,我想获取一个类类型来实例化。在ObjectiveC中,我做了类似的事情:

@implementation CommonClass
- (Class) secondaryAnnotationClass {
    return [MKAnnotationView class]; // abstract implementation, just return default class
}
@end
@implementation SubclassFoo
- (Class) secondaryAnnotationClass {
    return [FooAnnotationView class]; // my specific annotation class
}
@end
@implementation SubclassBar
- (Class) secondaryAnnotationClass {
    return [BarAnnotationView class]; // my specific annotation class
}
@end

那么我该如何在Swift中重新创建呢?我认为它类似于以下内容,但我还没有做正确的事情让编译器将简单的红点带走。

class CommonClass {
    var secondaryAnnotationClass:Type {
        return MKAnnotationView.self // abstract implementation, just return default class
    }
}
class SubclassFoo:CommonClass {
    var secondaryAnnotationClass:Type {
        return FooAnnotationView.self // my specific annotation class
    }
}
class SubclassBar:CommonClass {
    var secondaryAnnotationClass:Type {
        return BarAnnotationView.self // my specific annotation class
    }
}

似乎为了让Swift的类型系统保持高兴,我真正需要说的是,我不仅会返回一个Type(它真的是Class的替代品吗?),但它会是MKAnnotationView或其子类之一。

1 个答案:

答案 0 :(得分:1)

您可以secondaryAnnotationClass返回MKAnnotationView.Type

class CommonClass {
    var secondaryAnnotationClass: MKAnnotationView.Type {
        return MKAnnotationView.self
    }
}

class SubclassFoo:CommonClass {
    override var secondaryAnnotationClass: MKAnnotationView.Type {
        return FooAnnotationView.self
    }
}

class SubclassBar:CommonClass {
    override var secondaryAnnotationClass: MKAnnotationView.Type {
        return BarAnnotationView.self
    }
}

使用此方法,如果您需要使用特定于FooAnnotationViewBarAnnotationView的方法或属性,则必须进行向下转换。例如:

class FooAnnotationView: MKAnnotationView {
    func myFunc() {
        print("Foo")
    }
}

let subclassFoo = SubclassFoo()
let annotation = subclassFoo.secondaryAnnotationClass() as! FooAnnotationView
annotation.myFunc() // Prints: "Foo"
相关问题