Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • class
  • classForCoder
  • classForKeyedArchiver

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

enter image description here

like image 722
Jasper Blues Avatar asked Jun 05 '14 11:06

Jasper Blues


2 Answers

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.

like image 84
Sulthan Avatar answered Oct 25 '22 13:10

Sulthan


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

like image 20
Edwin Vermeer Avatar answered Oct 25 '22 12:10

Edwin Vermeer