3

I'm looking through the code for SWRevealViewController, a popular library/cocoapod and in the SWRevealViewController.h I noticed the following:

@class SWRevealViewController;

I know when to use forward class declarations of headers in other header files, but I don't understand what benefit this declaration is providing when it is in the same class. Am I missing something or is this code not doing anything?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
arc4randall
  • 3,275
  • 3
  • 27
  • 40

2 Answers2

3

There is no need for that line at all. But there is a need for the forward declaration of the protocol.

Typically you see a forward declaration of the class when the the protocol is declared before the class is and the protocol needs to make references to the class.

In this cases the class is declared before the protocol. So the protocol must be declared forward since the class makes a reference to the protocol (in the delegate property).

There is no need to forward declare both the class and the protocol.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
3

You're correct — the @class forward declaration does nothing if there aren't any other declarations making use of it before the @interface for that class appears.

And in the current state of SWRevealViewController.h on github, the declarations appear in the following order:

@class SWRevealViewController;            // fwd declaration of class
@protocol SWRevealViewControllerDelegate; // fwd declaration of protocol
@interface SWRevealViewController;        // actual class definition
@protocol SWRevealViewControllerDelegate; // actual protocol definition

With that ordering, the class definition requires the forward declaration of the protocol, but the forward declaration of the class is unused.

However, it doesn't cause any harm, either. If the author were to reverse the positions of the class and protocol definitions, it'd be the other way around (the protocol would need the forward declaration of the class, and the forward protocol declaration would be unused). It's simply a belt-and-suspenders matter of style.

jtbandes
  • 115,675
  • 35
  • 233
  • 266
rickster
  • 124,678
  • 26
  • 272
  • 326