-7

I use below line of code to allocate an Object(Suppose my Object name is Car) dynamically.

[self initliazieObject:[Car class]]

- (id)initliazieObject:(Class)model{

    id record = [[model alloc] init];
    return record;
}

How I can do this in swift 3.

Phillip Mills
  • 30,888
  • 4
  • 42
  • 57
iShameem
  • 101
  • 9

1 Answers1

4

Exactly as in Objective-C. Try this in a playground:

class Car : NSObject {}
func factory(type:NSObject.Type) -> NSObject {
    return type.init()
}
let c = factory(type:Car.self)
print(type(of:c)) // Car

(We can get fancy and do clever things with generics or Self to specify the type of the returned object more precisely, but my goal in this code is simply to do things the dumb way, just like Objective-C.)

matt
  • 515,959
  • 87
  • 875
  • 1,141