ios - Create objects dynamically in Swift -


in objective-c had category:

@implementation nsobject (entity) + (instancetype)entity{     class cl = self.class;     nsobject *obj = [[cl alloc] init];      return obj; } @end 

let's assume there classes , b:

@interface : nsobject @end  @interface b : nsobject @end 

and can use static entity method create objects like:

nsobject *o = [nsobject entity]; // type of nsobject *a = [a entity];               // type of b *b = [b entity];               // type of b 

how can write category in swift? know it's possible create object knowing type let s = nsstring.self; var str = s.init(), here don't know class, should self.self has no sense , doesn't work sure.

thanks in advance

as mentioned in comment, reason there no base class in swift. can still implementing own base class or subclassing nsobject.

class : nsobject {} class b : nsobject {}  extension nsobject {     class func entity() -> self {         return self.init()     } }  a.entity() b.entity()  nsobject.entity() 

Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -