Search code examples
iosobjective-cmacosswiftintrospection

Create objects dynamically in Swift


In Objective-C I had a category:

@implementation NSObject (Entity)
+ (instancetype)entity{
    Class cl = self.class;
    NSObject *obj = [[cl alloc] init];

    return obj;
}
@end

Let's assume there are classes A and B:

@interface A : NSObject
@end

@interface B : NSObject
@end

And then I can use static entity method to create objects like:

NSObject *o = [NSObject entity]; // type of NSObject
A *a = [A entity];               // type of A
B *b = [B entity];               // type of B

How can I write that category in Swift? I know it's possible to create an object by knowing the type like let s = NSString.self; var str = s.init(), but here I don't know the class, that should be something like self.self which has no sense and doesn't work for sure.

Thanks in advance


Solution

  • As I mentioned in my comment, the reason is that there is no base class in Swift. You can still do it by implementing your own base class or by subclassing NSObject.

    class A : NSObject {}
    class B : NSObject {}
    
    extension NSObject {
        class func entity() -> Self {
            return self.init()
        }
    }
    
    A.entity()
    B.entity()
    
    NSObject.entity()