Is there a Prefix Header (or something with this functionality) in Swift? - swift

Is there a way to get the functionality of a prefix header in Swift? I don´t want to import external libs in every file where they are used.

No. But you don't need it — there's no cost to import UIKit beyond the time it takes you to type twelve characters. (Or use an Xcode New File template that has them there already.)
That's the TLDR. For the whole story, read on...
In (Obj)C, the old way to make API available for use in a source code file was textual inclusion. The preprocessor would see your #import <Foundation/Foundation.h> directive and copy all the text from that header file (and from any other headers it includes, and the headers they include, and so on) into your source file before passing it off to the compiler. As you might expect, recompiling thousands of lines of system header declarations for each file in a project wasn't so performant.
So, we got precompiled headers some years ago—you'd put your common #imports in one place, and the compilation step for those parts would be done once, with a result that the compiler backend could reuse for each file in your project. But that had its problems, too: there's a maintenance burden to keeping your PCH happy, and it doesn't let you restrict the namespace used in each source file (i.e. if you want one .m file in your project to see only the symbols it needs to use, and not all the other stuff used elsewhere in your project).
And on top of that, textual inclusion has an underlying fragility problem. If you #define something above your #import lines, and that define changes a symbol used in the imported headers, those headers will have compile errors (or fail in more subtle ways, like defining the wrong API). There are conventions to keep that from happening, but conventions aren't enforced — you're always a typo / new team member / bad merge away from everything falling apart.
Anyway, textual inclusion wasn't so great, even with precompiled headers, so in Xcode 5 Apple introduced Modules. (Actually, not just Apple. They're in the LLVM/Clang compiler suite, so they're open source.) Modules are based on semantic import, not textual inclusion — that is, a module tells the compiler at an abstract level what API symbols it makes available to your source code, rather than pasting in the text of those symbols' definitions — so they're not fragile, and they're individually precompiled on the back end so building your project stays fast.
Modules are the default for ObjC projects now. (Notice that if you create a new ObjC project, it doesn't include a precompiled header anymore. You can turn modules off, so if you have an old project you might still be using textual inclusion and precompiled headers.) You can find out more about ObjC modules in Session 404 from WWDC 2013.
Why all this business about ObjC? We're talking Swift, right? Well, Swift is based on a lot of the same infrastructure.
Swift uses modules from the start, so it's always based on semantic import. That means there's no build-time performance hit and no fragility. All that Swift import does is tell the compiler what symbols you need (and the linker where to find them when producing your binary executable).
So the only cost to putting the same imports at the top of every file is the typing. And that's a necessary cost — in Swift, the source file is a semantic unit, and there's real meaning to deciding what goes into it. For example, the behaviors of many of the Swift standard library types change if you import Foundation, to enable bridging with Cocoa collection and value types — if there's a part of your app that wants to work strictly with Swift collection and value types, you might not want to import Foundation (or Cocoa or UIKit or something else that includes it).
Update: Furthermore, what you choose import in a Swift file has real meaning.
For example, how the compiler optimizes generics and static/dynamic dispatch depends on what declarations are visible in a given file, so if you import more than you need to, you may generate slower code. So generally, it's best to import only what you need.
Explicit imports also help with clarity and readability. If imports were project-wide, then when you copy-paste code out of one project and into another you'd see lots of errors in the new location... and it'd be a lot less clear what imports you need to resolve them.
"But I hate putting the same several imports at the top of every file all the time," you say. Let's think about that a little.
Do you really need several? Most modules transitively import their dependencies. You don't need to import Foundation if you're already importing Cocoa (OS X) or UIKit (iOS/tvOS/watchOS). And if you're writing a SpriteKit or SceneKit game, for example, you automatically get UIKit/Cocoa (for whichever platform) and Foundation for free.
Do you really need the same in every file? Sure, you're in a UIKit project so you're using UIKit almost everywhere. But that's just one import, twelve characters at the top. Maybe your project is also using Contacts or Photos or CoreBluetooth or HealthKit... but it probably doesn't need to use all of those in every single type you define. (If it does, your code probably suffers from poor separation of concerns.)
Are you really managing import statements all the time? I don't know about your projects, but in most large projects I've worked on, I'd say at least 90% of the development activity involves editing existing source files, not creating new ones... after starting up work on a project or major feature, very seldom are we (re)defining the set of source files or their dependencies. And there are shortcuts that can help with (among other things) setting up imports, like Xcode file templates.

Create a Objective-C Bridging Header file:
[New File→iOS→Source→Header File]: Bridging-Header.h
Go to this new header and import your external libs:
#import Module1Name;
#import Module2Name;
...
Go to Build Settings, set the path of Objective-C Bridging Header:
[Target→Build Settings→Swift Compiler - Code Generation→Objective-C Bridging Header]: $(SRCROOT)/.../Bridging-Header.h
Then you can use external libs in every file without import code.
References:
Third Party Swift Frameworks
Importing Objective-C into Swift

There is a -enable-bridging-pch feature. But it seems that not working in Xcode 9 :(
I decided to write this ansewer just to fully cover the topic.

You can create module that will import yours dependencies and import only it.
For example call Core. It will contain only single swift file with imports.
Every import should begin with #_exported keyword.
For example:
#_exported import UIKit;
#_exported import Combine;

Related

Does the Import Statement add the entire framework/library to your project

I'm trying to get a better understanding of what the Import statement does. According to this post:
As far as performance and binary size goes, any unused symbols are
already optimized out of the final binary by the Swift compiler. If
there’s no reference to it at compile time then it’s removed, meaning
that importing a framework but not using particular parts of it
shouldn’t have any negative implications.
The way I read this, is only those portions of the framework that you utilize are imported into your project
Yet in the same post above the fellow says:
We see that there are more precise imports that can be used if one is
concerned about compile time. Such as import
UIKit.UITableViewController
This seems to contradict the first statement. Full post Here
Thanks!

Scala: What's the easiest way to #include a file

What's the easiest way to include a file in a Scala source file?
Scala lacks first class imports and deports. I like to structure my package / project dependencies in a form of quasi multiple inheritance. For me this really helps in producing clean and effective design. I did the same thing with C# name spaces. Unfortunately neither C# nor Scala's syntax really support this methodology /strategy.
import name1.name2
no longer includes the name1 name-space so each level must be imported on a separate line, which rather undermines the hierarchy. And even previously a package could only inherit from one parent. The current system is very un-DRY, with constant repetition of imports. Of course I could use IDE templates, but templates are still not DRY. In my view complicated templates IDE are not a good solution (HTML / CSS for example). This strikes me as particularly bad in JavaFx / ScalaFx files where the import list is sometime longer than the class definition. So the best solution seems to be create an include file for each package with all the common imports and then
#include MeaningfulNameWithoutStops
Do I need to write a compiler plug-in to achieve this?
Or is there any thing else out there that could fulfil this functionality?
Should the compiler plug-in be relatively small and straightforward project?
You can include an entire package with the wildcard _ character
import name1._

How do I import code in Pascal?

What's the Pascal way to do C's #include "code.h", Python's import code, etc.?
Pascal uses
uses
to import other modules.
While you can explicitly {$INCLUDE a file it's rarely done other than for configuration files containing compiler switches. The only time I've ever done it was long ago when I wanted two versions of the code identical except one used coprocessor-only datatypes and the other didn't. (And how many people these days even know that single and double types used to require either an expensive additional chip or a slow emulator?)
If you include the same code in two places you will get two copies of it in your .EXE. If you include the same type definition in two places you'll get two types with the same name and since Pascal uses strict typing they will not match.
The normal mechanic is as Greg Hewgill says, to use the file you want. Anything that appears in the interface of the file you use is visible, anything that's only in the implementation is not visible. This is an all-or-nothing process, you don't specify what you are bringing in. Think of the C# using command.
Unlike the C# version it's absolutely mandatory. You can't use fully qualified names to get around it.

In Python, is the idiom "from Module import ClassName" typical?

Since I prefer small files, I typically place a single "public" class per Python module. I name the module with the same name as the class it contains. So for example, the class ToolSet would be defined in ToolSet.py.
Within a package, if another module needs to instanciate an object of class ToolSet, I use:
from ToolSet import ToolSet
...
toolSet = ToolSet()
instead of:
import ToolSet
...
toolSet = ToolSet.ToolSet()
I do this to reduce "stutter" (I prefer to have stutter at the top of the file than within my code.)
Is this a correct idiom?
Here is a related question. Within a package, I often have a small number of classes that I would like to expose to the outside world. These I import inside the __init__.py for that package. For example, if ToolSet is in package UI and I want to expose it, I would put the following in UI/__init__.py :
from ToolSet import ToolSet
So that, from an external module I can write
import UI
...
toolSet = UI.ToolSet()
Again, is this pythonic?
To answer your first question, that is the idiom I use, and its use is supported by PEP8 the python style guide
it's okay to say this though:
from subprocess import Popen, PIPE
I like it as it reduces typing and makes sure that things go wrong immediately the file is run (say you mis-spelt an import) rather than some time later when a function using the import is run.
Eg suppose the module Thing doesn't have a Thyng member
from Thing import Thyng
Goes wrong immediately you run the .py file, whereas
import Thing
# ...
def fn():
Thing.Thyng()
Doesn't go wrong until you run fn()
As for your second question, I think that is also good practice. It often happens to me when I factor a single large.py into a directory with an __init__.py and implementation files. Importing things into the __init__.py keeps the interface the same. It is common practice in the standard libraries too.
Yes. Both are idiomatic Python in my opinion.
I tend to use the from module import name form for some modules in the standard library, such as datetime, but mostly for closely related modules, or names that are frequently used in the module. For example, I typically import ORM classes in this way.
I tend to use the import module form for some standard modules (especially os and os.path) and for names that are not very distinctive (like database.session and cherrypy.session being two different kind of sessions) and for name that are used infrequently where the mention of the module name improves readability.
In the end, there are a few rules of thumb (such as import os.path), but which form to use is largely a matter of judgement, taste and experience.
To address if it is pythonic, take a look at what is generally the definitive answer on the internet: http://effbot.org/zone/import-confusion.htm
Also take a look at ~unutbu's link which discusses this in greater detail.
I use from itertools import chain, ifilter, islice, izip all the time, because it allows me to program as though those were built-in methods, which to my way of thinking they really ought to be.
Once, in a frenzy of misguided correctness, I went through a big block of code and replaced from datetime import datetime with import datetime. This was a good example of Mark Twain's observation that a man who picks up a rat by the tail learns something that can be learned no other way. It certainly set me straight on why it's OK to use from x import y.

How bad is it, in theory, if every class would include every other class?

Imagine an iPhone app with 30 classes. Every class has to interact with every other, so every class includes 29 other classes + foundation framework.
I want to understand what's exactly happening when including a class. Does this duplicate the size in memory for that class in the app? Is it harmful to memory footprint and performance on the iPhone? Maybe someone knows this in detail and can explain.
Please miss that this would not be a good architecture. It's a hypothetic question about what "include" does to memory and performance.
The only case where you might run into a performance hit is at compile time. By using #import "MyClass.h" instead of #class MyClass in the header for a class, it will be recompiled when the interface to MyClass changes. This will add a little to your total compile time, which may add up over a large project.
EDIT (8/29/2009): I changed #include to #import in the above answer, as that's used in ObjC to prevent repeated includes of headers.
There is a difference between including and instantiating. If every class attempts to instantiate the other, then yes this is very bad.
Although, if you are simply providing a reference to the file so that any class can be instantiated from anywhere, the only issue you'll likely run into is that of bad paths if you try to change stuff around.
changing the name of one file (or class), for example, means you now have to go and rectify 29 other bad references to that path.
As far as I'm aware, simply including the file (at least in languages I'm familiar with) will not adversely affect your performance.
Usually the including and scoping, object orientation etc is only a utility for the programmer. An illusion of order if you will. Down at the machine code level, you can access any variable of your process everywhere. That you have to include headers that are used somewhere else in your program is only a way that language creators use to limit the things you currently have to think about, throw out duplicates etc. and that the compiler can give you help in verifying that your "description" of the program works right.
You only make your executable bigger if you link stuff into it. You only make it slower, as Evernoob hinted at, if you produce lots of instances etc. Just to make types and definitions "known" to other classes should not cause any performance issues at runtime, but it usually will increase compile time.
In general trying to keep dependancies down is more about not having to change a ton of code when one class changes.
Simply including lots of files, it not necessarily bad - all it would do is increase compile time but the increase would not be really noticeable until you got to hundreds of files (if that).
Something else to keep in mind is that there's a difference between including from a header vs. a class file. If you include a class definition from a header that in turn includes a header you are in, you have a circular reference and you'll have to declare one of the class references as a forwarded class with the #class directive. In fact the standard is theoretically to use "#class" in the header file and "#import" in the implementation, but usually you don't run into classes having references for each other so #import in the header works just as well, and is a little less typing.