Home > database >  Swift - import all of framework VS part of it
Swift - import all of framework VS part of it

Time:10-04

My background is from C and Python and when I import in these languages it is always a good practice to only import what will be used, mainly in Python. In Swift I know there is a way to do this, but does it really make any difference?

When I'm going to do some extension, some model or enum I only care what will be needed.. But does it really matter? It makes a difference?

Example of my code:

/* Gui Reis    -    [email protected] */

/* Libraries */
// import CoreData
import struct CoreData.UUID


struct Garden {
    let id: UUID
    let title: String
    let bio: String
}

My question is with a focus on performance mainly: does it make a difference to the compiler, since I'm specifying exactly what I want to import and I'm not importing anything else.

I believe the compiler should already do this filter, but me doing it, does it make a significant difference? Is it a good practice in Swift?

CodePudding user response:

The feature of importing just a single symbol from a module is mainly for avoiding name conflicts.

For (a very contrived) example, let's say there is a module A which declares the classes Foo, Bar, and a module B which declares the classes Bar, Baz.

In your file, you import A and use Foo and Bar many times. Later, there is a change that requires you to use B.Baz. At this point, importing the entire B would make Bar ambiguous between A.Bar and B.Bar, and you would have to change all existing occurrences to A.Bar, when all you wanted to use was B.Baz. To solve this problem, you could say import class B.Baz instead.

As for performance, while importing just a single symbol does potentially make the job for the compiler easier, as it does not need to search as much to resolve a name that you have written. However, I highly doubt that this is a significant difference compared to all the other more complicated things that the compiler does, such as overload resolution and type inference.

This also makes no difference at all at runtime, because import declarations does not determine what frameworks are linked in the compiled binary as you seem to be implying. import declarations are simply a compile time thing that determine what names are available in the file.

  • Related