3

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!

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Zarochintsev
  • 221
  • 2
  • 10

1 Answers1

8

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()
}
Community
  • 1
  • 1
bzz
  • 5,556
  • 24
  • 26
  • Please have a look at http://stackoverflow.com/help/how-to-answer: **Provide context for links** Links to external resources are encouraged, but please add context around the link so your fellow users will have some idea what it is and why it’s there. Always quote the most relevant part of an important link, in case the target site is unreachable or goes permanently offline. – Martin R Jun 22 '14 at 17:37
  • 1
    Note that `AnyClass` is a more general way to write the type of any type corresponding to a class – newacct Jun 23 '14 at 08:31
  • 1
    @newacct I know. The solution only works for NSObject subclasses. The usage of `AnyClass` will result in error : `'AnyObject' is not constructible with '()'` – bzz Jun 23 '14 at 10:34