Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a class and method to create an instance of a class? [duplicate]

Tags:

swift

I just started learning Apple Swift I can not deal with the problem, I have methods to help Objective-C please rewrite on Apple Swift

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

Call method (User Inherited from NSObject):

[self setClass:[User class]];

How to repeat such actions on Apple Swift? Thank you!

like image 954
hdshfkdsjk Avatar asked Jan 19 '26 17:01

hdshfkdsjk


1 Answers

Here is an article about instantiating classes by name in Swift. The problem is solved by creating an Objective-C class with method

+ (id)create:(NSString *)className
{
    return [NSClassFromString(className) new];
}

and calling it from Swift. The source code is on GitHub: https://github.com/ijoshsmith/swift-factory

UPDATE:

Here is a simpler solution:

var clazz: NSObject.Type = TestObject.self
var instance : NSObject = clazz()

if let testObject = instance as? TestObject {
    println("yes!")
}

Of course, the class must be a subclass of NSObject.

Your function will then be:

func setClass (myClass: NSObject.Type){
    var object = myClass()
}
like image 63
bzz Avatar answered Jan 22 '26 08:01

bzz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!