Generics call with Type T in Swift

后端 未结 7 978
逝去的感伤
逝去的感伤 2021-02-12 17:14

In my application I want to create an generic method which creates an array of object depening on the given type T.

I created the following function:

fun         


        
7条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-12 18:05

    I think it is a bug.

    You can work around it by making the class a sub-class of NSObject or mark constructor of base class with @required

    import Cocoa
    
    class A : NSObject {
        init() { }
    }
    class B : A {}
    class C : A {}
    
    func Create () -> T {
        return T()
    }
    
    println(Create() as A)
    println(Create() as B)
    println(Create() as C)
    
    //<_TtC11lldb_expr_01A: 0x7f85ab717bc0>
    //<_TtC11lldb_expr_01B: 0x7f85ab451e00>
    //<_TtC11lldb_expr_01C: 0x7f85ab509160>
    
    class D {
        @required init() { } 
    }
    
    class E : D {
        init() { }
    }
    
    class F : D {
        init() { }
    }
    
    func Create2 () -> T {
        return T()
    }
    
    println(Create2() as D)
    println(Create2() as E)
    println(Create2() as F)
    
    //C11lldb_expr_01D (has 0 children)
    //C11lldb_expr_01E (has 1 child)
    //C11lldb_expr_01F (has 1 child)
    

    Not sure why @required solve the problem. But this is the reference

    required

    Apply this attribute to a designated or convenience initializer of a class to indicate that every subclass must implement that initializer.

    Required designated initializers must be implemented explicitly. Required convenience initializers can be either implemented explicitly or inherited when the subclass directly implements all of the superclass’s designated initializers (or when the subclass overrides the designated initializers with convenience initializers).

提交回复
热议问题