-1

Should I include import for Foundation while importing UIKit (which has Foundation import in itself)?

Could UIKit work without Foundation in the future and in theory break my code down the road?

Paweł Brewczynski
  • 2,665
  • 3
  • 30
  • 43

4 Answers4

3

Always import the lowest level you can get away with:

  • If your file is pure library Swift, import nothing.

  • If your file needs Foundation types, import Foundation.

  • If your file needs UIKit types (they all start with UI), import UIKit.

  • If your file needs SwiftUI types, import SwiftUI.

You should do exactly one of the above. As for your original question, UIKit itself imports Foundation (as you have rightly said). Therefore if a file imports UIKit, it does not need to import Foundation explicitly, and you should not import it explicitly.

UIKit will not magically lose its ability to access Foundation types in the future. UIKit without, say, NSString would be a metaphysical impossibility. Conversely, if NSString went away, UIKit itself would go away and that would be the breakage.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Do we know that SwiftUI implies UIKit? Can it make sense to import both? (I agree completely with the other situations.) – Rob Napier Mar 23 '22 at 18:18
  • 1
    @RobNapier I assume it does because I've seen code here on SO that was pure UIKit but the programmer had (wrongly) imported SwiftUI. However, I could cut that line if I'm wrong about that. – matt Mar 23 '22 at 18:38
  • 1
    Yeah, it definitely "works" (SwiftUI almost certainly *does* import UIKit because stuff compiles). And it's hard to imagine they'll ever break that, even if SwiftUI gets to a point where it doesn't "need" UIKit for anything, so your hierarchy is probably right. – Rob Napier Mar 23 '22 at 19:52
1

No, you do not need to import both Foundation and UIKit. UIKit is enough if you use any UI* types. If you do not use any UI* types, you do not need UIKit and can leave only Foundation.

Oleg991
  • 311
  • 2
  • 7
0

No you only need to import Foundation for classes that don't use UIKit.

It's possible you will want to use the classes that import Foundation with SwiftUI or AppKit in the future, so it's best to keep your UI code separate from you non-UI code.

I personally won't even use UIImage or UIColor in view models, because as I think view models should be Foundation only.

shim
  • 9,289
  • 12
  • 69
  • 108
Nathan Day
  • 5,981
  • 2
  • 24
  • 40
-1

UIKit is much more likely to be made redundant before Foundation, SwiftUI is already becoming the replacement for UIKit, and Foundation is much more general than UIKit, for example if you have something that only needs foundation, it can potential work in a UIKit application, a SwiftUI application, a MacOS ApplicationKit application, a TVOS application, a Comandline tool that has no GUI.

Nathan Day
  • 5,981
  • 2
  • 24
  • 40