19

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.

2 Answers 2

27

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
2
  • as of Swift 3? I believe this feature was in Swift since the beginning.
    – Sulthan
    Commented Jan 12, 2017 at 15:47
  • 1
    I suppose you're right. The main reason to write "as of Swift 3" was that I cannot be sure whether it will be true in Swift 4+. I removed the first "as of Swift 3", because it's nearly impossible that Apple will remove the feature from the language.
    – artyom.stv
    Commented Jan 12, 2017 at 15:53
1

It's not even with Swift 5 possible to directly alias an import-statement!?

But fortunately, I could workaround it with something like:

import typealias MyModule.MyInnerClass

I mean, if we are the module's developer, simply move the alias into the module, like:

public typealias MyInnerClass = MyClass.MyInnerClass

public class MyClass {
    public class MyInnerClass {
        // Some cool logic here...
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.