Diego Freniche
Diego Freniche

Reputation: 5414

Why using new() class method to create an object in Swift doesn't compile?

I wasn't a big fan of new in Objective-C. But this question raised the doubt. Why this does not compile?:

let j = NSNumber.new()
var s = NSString.new()

Looks like new() is a regular class method. Although in Apple's doc is defined with back ticks around the name ??

class func `new`() -> Self!

So, the question remains. If new() is there in NSObject, why does not compile? File Radar?

Upvotes: 0

Views: 71

Answers (1)

Kirsteins
Kirsteins

Reputation: 27345

new is a reserved keyword and you have to escape it with backticks. This will work:

let string = NSString.`new`()

But I recommend using the "Swift" way as it shorter, cleaner and works for non NSObject kinds:

let string = NSString()

Upvotes: 3

Related Questions