skip to Main Content

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?

4

Answers


  1. 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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  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.

    Login or Signup to reply.
  4. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search