Swift generics not preserving type

前端 未结 4 776
借酒劲吻你
借酒劲吻你 2020-11-28 11:23

I\'m trying cast and/or generate a variable based upon the specified generic type. I understand there is no type erasure in swift, but it doesn\'t seem like the generics pre

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 11:46

    The problem is var instance = T() Initialisers are not virtual so the instance is always made with BaseClass()*. The following code uses a class function to work around the problem:

    class BaseClass {
        func printme() -> String {
            return "I am BaseClass"
        }
        class func makeInstance() -> BaseClass
        {
            return BaseClass()
        }
    }
    
    class DerivedClass : BaseClass {
        override class func makeInstance() -> BaseClass
        {
            return DerivedClass()
        }
    
        override func printme() -> String {
            return "I am DerivedClass"
        }
    }
    
    class Util {
        func doSomething() -> String {
            var instance = T.makeInstance()
            return instance.printme()
        }
    }
    
    var util = Util()
    println("\(util.doSomething())")
    

    I changed the implementation of printme() only because the original code didn't print anything in a playground for some reason.

    * I think this is still a bug.

提交回复
热议问题