Swift: import UIKit in each subclass?

In objective-C, we can do this:

and. Importing a file into a superclass

#import "MyAwesomeClass.h"

@interface MySuperViewController : UIViewController
@end

@implementation MySuperViewController
- (void)viewDidLoad {
  [super viewDidLoad];

  //MyAwesomeClass allocated, initialized, used
  MyAwesomeClass *awesomeClass = [MyAwesomeClass new];
}
@end

      

b. Using a file imported into a superclass into a subclass without re-importing it

@interface MySubViewController : MySuperViewController
@end

@implementation MySubViewController
- (void)viewDidLoad {
  [super viewDidLoad];

  //No compilation error, since MyAwesomeClass already imported in superclass
  MyAwesomeClass *awesomeClass = [MyAwesomeClass new];
}
@end

      

Trying to do the same thing in swift gives a compilation error:

and. importing UIKit into MySuperViewController

import UIKit
class MySuperViewController : UIViewController {
   @IBOutlet weak var enterPrice: UITextField!
}

      

b. Declaring and using UITextField object without importing UIKit into MySubViewController

class MySubViewController: MySuperViewController {
    // compilation error at below line
    @IBOutlet weak var myButton: UIButton!
}

      

Is there a way to avoid re-importing UIKit in the above scenario? Please suggest.

+3


source to share


1 answer


The short answer is:

Yes. I understand that you need to import all the frameworks you need in every Swift file in your project (this is a step by step requirement, not class by class. If you are defining 2 classes in one file, you only need one import at the top of the file.)



# Import / # include statements in C are preprocessor directives. It is as if the code in the included file was copied / pasted into the include folder. If you include the header in the superclass header, the superclass header now contains extended content. Therefore, when you include the superclass header in your subclass, the system frame headers are included as part of the superclass header.

Swift works a little differently.

+8


source







All Articles