8

Is there a way to always import a few libraries on every file? without putting them into a framework

for example, instead of having to do

--MySwiftFile.swift--

import UIKit 
import Foundation
import ...

I could do something like:

--SharedImports.swift--

import UIKit 
import Foundation
import ...

--MySwiftFile.swift--

import SharedImports.swift
Edward Ashak
  • 2,411
  • 2
  • 23
  • 38

1 Answers1

6

The answer is "No, and that's on purpose". Each file needs to know the context of the code that is contained within that file. It gets that context from the set of imports.

Now in the particular case of UIKit and Foundation, it should be the case that UIKit imports Foundation so I don't think you have to explicitly call out both in every file. In the examples above you should be able to get by with just

import UIKit

There are times, when defining your application's model for example, where you may want a file to bring in Foundation and not UIKit.

Scott Thompson
  • 22,629
  • 4
  • 32
  • 34
  • i put the two of them just as an example but you're right. what if i had a local framework in my project and in the framework these libraries were imported I still need to import them explicitly, no ? – Edward Ashak Mar 22 '16 at 22:11
  • Yes. Each file is compiled as a separate unit and each unit needs a complete context to know what's available to the code in that unit. – Scott Thompson Mar 22 '16 at 22:14
  • Somehow there is PrefixHeader.pch. You can do workaround: Create Objective-C file. Add all those libraries you want to have imported everywhere to PrefixHeader.pch and then import this Objective-C file via BridgingHeader... for sure doable and answer "definite NO" is wrong. – Adas Lesniak Mar 17 '19 at 17:34