Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to alias an import?

Tags:

swift

swift3

In c# when pulling in a library that has a lot of name collisions with existing code, there's a way to alias the import so you don't need to fully clarify the namespace for each use. eg:

using MyCompany.MyLibrary.Model as MMM

then you could do

MMM.MyObject

instead of

MyCompany.MyLibrary.Model.MyObject

With the recent update to swift 3.0, I've found some of my model objects are now colliding with the Foundation types, and I've been forced to prefix things that used to have an NS prefix in the class name with Foundation.classname. It would be great if I could type alias the import of my model library much like the c# example given above. Is this possible in swift 3.0? If not is there another strategy to avoid name collisions that would result in having to write the framework name in front of each type? I'm considering going back to prefixing my class names like we did in obj-c, but I'm trying to explore my options before I do that.

like image 241
Kevin DiTraglia Avatar asked Sep 16 '16 17:09

Kevin DiTraglia


People also ask

How do I rename an import react?

To use import aliases when importing components in React, use the as keyword to rename the imported component, e.g. import {Button as MyButton} from './another-file' . The as keyword allows us to change the identifying name of the import.

What does it mean to import a module with an alias give an example?

For example: Copy from utils import printer as myfunc. In this case the printer function in the utils module is being aliased to myfunc and will thus be known as myfunc in the current file.

How do I rename an import in TypeScript?

To import two classes with the same name, use the as keyword to rename one or both of the imports, e.g. import { Employee as Employee2 } from './another-file-2'; . The as keyword allows us to change the identifying name of the import.


1 Answers

Update 2021 for Swift 5;
No, but you can import all and alias (in separate file), read below for more details.

Generally

You can import a particular entity as well as the entire module:

import struct­ SomeModule.SomeStruct
import class­ SomeModule.SomeClass
import func SomeModule.someFunc

See the full list of "importable" entity types in the import-kind rule of Swift grammar.

Then you can create a typealias:

typealias SMSomeStruct = SomeModule.SomeStruct

And, as of Swift 3, there is no import declaration combined with aliasing.

Considering the Collisions with Foundation Entities

Say, you have a class SomeModule.NumberFormatter.

It is enough to create two typealiases in a separate Swift file (in an importing project) to prevent collisions:

import Foundation
import SomeModule

typealias NumberFormatter = Foundation.NumberFormatter
typealias SMNumberFormatter = SomeModule.NumberFormatter
like image 131
artyom.stv Avatar answered Oct 24 '22 12:10

artyom.stv