5

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

Jasper Blues
  • 28,258
  • 22
  • 102
  • 185

2 Answers2

8

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.

Sulthan
  • 128,090
  • 22
  • 218
  • 270
  • Useful to know, but doesn't really explain why 'class()' appears in the code-completion drop-down at all, let alone stuck-out. – Jasper Blues Jun 05 '14 at 23:47
  • yes, you _can_ create methods named `class`, `for`, `while` or other keyword by using backticks in your declaration: ``func `func`() -> Void { ... }`` – Cœur Jun 30 '17 at 15:55
7

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
Edwin Vermeer
  • 13,017
  • 2
  • 34
  • 58
  • Yes, noted that the class itself is an AnyClass type. Interestingly Birdy.classForCoder and Birdy.classForKeyedArchiver could be passed to the runtime, but not Birdy itself. (Next question) – Jasper Blues Jun 05 '14 at 13:23
  • You were right. I managed to find a proof your answer is the correct one. – Sulthan Jun 06 '14 at 11:24