Jasper Blues
Jasper Blues

Reputation: 28786

Swift : Why is the class method struck out

As long as a Swift class extends from NSObject we can pass it to the Objective-C runtime and ask it to introspect it for us.

We have three options:

. . however class is struck out. (See image). Why is this?

enter image description here

Upvotes: 5

Views: 1925

Answers (2)

Edwin Vermeer
Edwin Vermeer

Reputation: 13127

As you can see in the documentation, it's only available in Objective C and not in swift. See: https://developer.apple.com/documentation/objectivec/nsobject/1571950-class

I think this is because the AnyObject gives you enough information (More than the NSObject) for instance you can do NSStringFromClass(BaseObject) in swift instead of the NSStringFromClass([BaseObject class]) that you do in Objective C

Upvotes: 7

Sulthan
Sulthan

Reputation: 130191

That's because class is a keyword in Swift, therefore any valid method cannot be named class. In the same way you cannot create a method named for, while or other keyword.

I wasn't able to reproduce the strike-out with my methods, however, naming a method var (or other keyword) in obj-c makes it impossible to be called from Swift.

Edit

I was wrong. It's still possible to call class from Swift using

var clazz: AnyClass? = self.`class`()

However, then the compiler says:

'Class' is unavailable: use 'dynamicType' instead

So the answer by Edwin Vermeers is the correct one.

Upvotes: 8

Related Questions