2

I would like to instantiate an Object with a given Type. Here's the call to the function:

buildObjetFromType("data", typeClass: User.self)

Here's the function code:

public static func buildObjectFromType<T>(data: String, typeClass: T.Type) -> T{ 

    print(typeClass) // will print "User"
    var object:T?

    object as! T.Type // cast the object into an User -> NOT WORKING !

    // fill the object with the data, knowing 
    // return the object once it has been filled with the data.
}

here's my User class:

public class User {
    private var id:String?
    private var login:String?
    private var pwd:String?
    private var nom:String?
    private var prenom:String?

    public required init(){
        id = ""
        login = ""
        pwd = ""
        nom = ""
        prenom = ""
    }

    public convenience init(_login: String, _pwd: String){
        self.init()
        login = _login
        pwd = _pwd
    }

    public convenience init(_id: String, _login: String, _pwd: String, _nom: String, _prenom: String){
        self.init(_login: _login, _pwd: _pwd)
        id = _id
        nom = _nom
        prenom = _prenom
    }
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
Seb.M
  • 21
  • 1
  • 2
  • Where do you instantiate the object? `var object:T?` returns just `nil`. You need to call an `init` method somewhere. – vadian Mar 23 '16 at 13:30
  • well the instantiation I believe would be "object as! T.Type" or am I wrong ? T.init() won't work since it doesn't know what "T" is – Seb.M Mar 23 '16 at 14:53

1 Answers1

2

See: Instantiate an object of a generic type in Swift

Assuming all the classes you want to instantiate have a required initializer with no argument (you may want them to inherit from the same base class, and add this requirement to your function), you could do the following:

static func instantiate<T where T: BaseClass>(data: String, cls: T.Type) -> T {
    let obj = T()
    // do something with obj and data
}
Community
  • 1
  • 1
Clément Mangin
  • 423
  • 3
  • 8
  • 1
    You should flag this question as duplicate rather than post a duplicate answer from another Stack Overflow question. – JAL Mar 23 '16 at 14:13
  • Let's assume this is a possibility, how would I call a subclass of my BaseClass ? – Seb.M Mar 23 '16 at 14:57