首页 文章

动态(通用)继承自swift中的<T>

提问于
浏览
1

我没有找到任何解决方案,并且很有可能它不可能但我会试一试(如果不可能我会很乐意得到一个小解释为什么) .

我正在尝试在Swift中创建一个类,让我们称之为Foo,我希望FooChild继承自Foo . 到目前为止,没有问题 . 问题是,我希望Foo动态地继承“任何类”,可能是通用类型 .

就像是

class Foo<T> : <T>{

}

class FooChild : Foo<NSObject> {

}

class FooChild2 : Foo<UIview> {

}

我希望FooChild和FooChild2都继承自Foo,但是我希望foo从NSObject继承一次,并且从UIView继承一次(在示例中使用随机类) .

那可能吗?即使在我将以某种方式桥接的Objective-C代码中 .

1 回答

  • 1

    Swift 1.2

    不,那是不可能的 .

    你能做的是:

    protocol Foo { }
    
    class FooChild1: NSObject, Foo { }
    
    class FooChild2: UIView, Foo { }
    

    Swift 2

    是的,现在这是可能的 .

    非泛型类可以继承自泛型类 . (15520519)

    见:Xcode 7 Beta Release Notes,章"New in Swift 2.0 and Objective-C",第"Swift Language Features"节

    例如 . 以下是可能的:

    import UIKit
    
    class Foo<T> { }
    
    class FooChild: Foo<NSObject> { }
    
    class FooChild2: Foo<UIView> { }
    
    let fooChild = FooChild()
    
    let fooChild2 = FooChild2()
    

    此外,在Swift 2中,如果您需要Swift 1.2示例中的协议 Foo 来提供某些默认行为,则可以使用默认协议实现 .

    您可以使用协议扩展为该协议的任何方法或属性要求提供默认实现 . 如果符合类型提供其自己的必需方法或属性的实现,则将使用该实现而不是扩展提供的实现 .

    见:The Swift Programming Language,Chapter "Protocols",Section "Providing Default Implementations"

相关问题