In objective-C we can do like this:
a. Importing a file in super class
#import "MyAwesomeClass.h"
@interface MySuperViewController : UIViewController
@end
@implementation MySuperViewController
- (void)viewDidLoad {
[super viewDidLoad];
//MyAwesomeClass allocated, initialized, used
MyAwesomeClass *awesomeClass = [MyAwesomeClass new];
}
@end
b. Using the file imported in superclass, in 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 compilation error:
a. importing UIKit in MySuperViewController
import UIKit
class MySuperViewController : UIViewController {
@IBOutlet weak var enterPrice: UITextField!
}
b. Declaring and using an object of UITextField without importing UIKit in MySubViewController
class MySubViewController: MySuperViewController {
// compilation error at below line
@IBOutlet weak var myButton: UIButton!
}
Is there any way we can avoid re-importing UIKit in above scenario? Please suggest.
Short answer:
Yes. It's my understanding that you need to import all the frameworks you need in each Swift file in your project (it is a file-by-file requirement, not class by class. If you define 2 classes in a single file, you only need one import at the top of the file.)
The #import/#include statements in C are preprocessor directives. It is as if the code in the included file is copy/pasted at the location of the include. If you include a header in your superclass's header, the superclass's header now contains the expanded contents. So when you include the superclass header in your subclass, the system framework headers are included as part of the superclass header.
Swift works a little differently.
If you use any objective-C class in your Swift project and import UIKit in that class, you don't actually have to use the import UIKit
directive anywhere else in your project!
So basically:
#import "MyClass.h"
That's it! You are now free to delete your import UIKit
statements from every file. It's worth noting that stylistically and for code reuse purposes, it's better to have all of the imports in every file so everyone can see at a glance what dependencies there are, but when you are creating ViewControllers and such I think it's kind of silly to have to import UIKit in every single file. Everyone knows it has a dependency on UIKit and chances are you won't be reusing the UI in another project anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With