Does `import` order matter?

Hi,
Just interesting does import order matter? it could be anything performance/override...
For example here this (I know some modules can be omitted).

import Foundation
import UIKit
import XCTest
import ThirdPartyModule
@testable import MyModule
2 Likes

I’m going to hesitantly say the order is not supposed to matter. This is implied by the fact that the official formatter has a rule that puts them in alphabetical order.

In reality however—due presumably to unresolved bugs—order can end up mattering whenever some of the imports have modifiers. The compiler applies the first one it sees, and then when it comes to the next instance of a similar‐looking import, it may think it is already covered and not realize it needs to elevate the access. Modifiers that sometimes cause problems include @testable and @_exported. So if some imports appear to be malfunctioning, try putting the most‐elevated ones first. For example, if you make sure @testable imports are at the top, then even if something further down repeats the import in a narrower form—even indirectly—, you will still have the testable access that was granted when the compiler first encountered it.

But don’t bother worrying about this until you actually encounter a situation where the compiler gives you trouble. They are rare corner cases, and they aren’t supposed to happen anyway. Odds are they get fixed before you ever encounter one.

5 Likes

Import order does not matter. If a module relies on other modules, it needs to import them itself.