[[+content_image]]
D
D
dev_nikita_ysacov2014-06-22 18:33:06
iOS
dev_nikita_ysacov, 2014-06-22 18:33:06

How to pass a class to a method and create an instance of the class?

Good day, in the good old Objective-C, you could create a method, and pass the class:

- (void)setClass:(Class)aClass {
    NSObject *object = [[aClass alloc] init];
}

Method call (User inherited from NSObject):
[self setClass:[User class]];
How can I repeat the same actions on Apple Swift (as I did not twist and torture, nothing happened, all hope is on you)?
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
O
one pavel, 2014-06-24
@onepavel

class One : NSObject {
    func foo() {
        NSLog("foo")
    }
}
var cls1 : AnyClass = NSClassFromString("One")
var inst1:One = cls1.alloc() as One
inst1.foo()
        
var cls2 : AnyClass = One.superclass()
var inst2:One = cls2.alloc() as One
inst2.foo()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question