Swift Generics, create derived object

70 views Asked by At

I have a Store class which is coded as generic, so that it can manage all kind of classes that are derived from a common base class.

The store has a new() method, which creates and returns the class it currently manages. In theory, it should return the derived class.

Unfortunately, the store returns always the base class. Here is code snippet that explains it:

import UIKit

class Base: NSObject {

    var ID:Int=0
}

class Adress:Base
{
    var name = ""
}

class Store<T:Base>  {

    var nextID:Int = 0

    func getNextID()->Int {
        return ++nextID;
    }


    func new() ->T{

        let n = T()
        n.ID = getNextID()
        return n
    }
}




let store = Store<Adress>()
var adr:Adress = store.new()  // should be Adress, but is Base
adr.name = "Tom"              // crash here, because adr is not an Adress 

If I debug the new() method inside the Store, it creates an Adress object. But in the calling code, it is suddenly a Base object.

Any idea whats going wrong here?

1

There are 1 answers

1
Ivan Rigamonti On BEST ANSWER

I do not exactly understand your intensions with above code. But if you substitute

class Store<T: Base> {

by

class Store<T: Adress> {

then the variable adr is of type Adress. Following statements work then

println(adr.name) // displays "Tom"
println(adr.ID)   // displays "1"