Currently, all my imports are scattered throughout my project. I want to place all imports in a single file so that it's easy to see what all libraries are used by the app. Then, I can import this file everywhere.
While this is easy to achieve in C++ with its header files, I'm not sure how to do this in swift... as there are no headers in swift and its not possible to import a file in swift. As explained in this article, it is possible to import a module, functions, classes, enum, variables, type aliases etc... but not file.
I was visualizing a file called SystemImports.swift with the following code:
import Foundation
import UIKit
import SwiftUI
import NotificationCenter
import UserNotifications
import WidgetKit
...
Then I can import this file every other file. Is something like this possible in swift?
I have a static library containing a SwiftUI View which imports SwiftUI.
import Foundation
import SwiftUI
public struct MessageView: View {
....
}
The App protocol is in the App target with the following code:
import <Static Library>
//import SwiftUI
@main
struct HelloIOSApp: App {
...
}
I have imported a Static Library which imports SwiftUI. When I import that Static Library in my App target (as shown above), it doesn't work. I get compilation errors which can be solved by uncommenting the SwiftUI import in the above code. But according to this stackoverflow answer, it should've worked.
While the above approach is not working, what I really wanted was to have a file of only imports and then import that file everywhere. Is this possible in swift?
There is no way to achieve this in Swift.
The Obj-C way of prefix headers is not only not possible in Swift, it isn't good practice either. You shouldn't import unnecessary dependencies into every single one of your files. Only import modules that the specific file directly depends on. This is why transitive imports aren't a thing either.
The fact that a module depends on another module doesn't necessarily mean that you automatically have to import the transitive dependency every time you use said library. For instance, if you have a library called MyAnalytics
, which internally depends on FirebaseAnalytics
, that doesn't necessarily mean that every time you import MyAnalytics
you actually need to use (and hence import) FirebaseAnalytics
as well. You only need to import transitive dependencies if your direct dependency exposes a type of the transitive dependency in its public interface and hence you have to access a type from the transitive dependency in your code directly.
To translate this to your use case - just because your UI library import SwiftUI, that doesn't mean you should have to import SwiftUI to use the library. Hence an automatic import of SwiftUI based on the import of your UI library wouldn't be desired. You are directly depending on SwiftUI, because you are using SwiftUI types (namely, App
) directly - so you should be importing SwiftUI directly to make the dependency clear.