简体   繁体   中英

How to import a Swift framework globally?

I want to have a way to import my Swift Cocoapods globally in every class, how can I achieve this?

I tried a lot of things and they didn't work. Here are some ways I haven't tried and thought may be possible if found a way to work them:

Have a general import statement like UIKit and put everything in there. (Edit: This failed)

Somehow put Swift frameworks in the Obj-C briding header and import the stuff in there.

You should be able to import it globally by adding @_exported before the import.

@_exported import Podname

However, like the previous posters mentioned, this is not recommended.

It's strongly discouraged in Swift because that would introduce implicit coupling between modules.

However, you can make a certain symbol available globally by declaring a typealias in the module that imports the other module:

import ModuleName
public typealias ClassName = ModuleName.ClassName

As of Swift4:

  • Being in a Swift project
  • Want to have another Swift project globally imported (and using cocoapods)

I just managed to do that by adding the following line to my bridging header:

#import <PodName/PodName-Swift.h>

How good/bad this practise is? Not sure, but I just wanted some extensions globally available in my project. this did the trick.

There is no way to do this. And this is not a bug, this is a language feature (so far, as speaking of Swift 2.2).

Swift uses modules (Apple introduced them in Xcode 5 for Objective-C) and each file is an semantic unit, so you need to explicitly inform Xcode which modules are exposed to defined file.

Not only there is no support for your described behaviour, but you shouldn't also try to bypass it. Using unnecessary (unused) modules could theoretically produce slower code (taking into account that compiler uses this information to its optimisation process).

You can manually achieve the same functionality by:

  • Creating the Objective-C Bridging Header file ;
  • Adding #import <UIKit/UIKit.h> to the Objective-C Bridging Header file (so that you don't need to repeat this for every single .swift file).

for pods you have to do like #import <SwiftyJSON/SwiftyJSON-umbrella.h>

A reason you wouldn't want to do this:

Imagine if both your frameworks would use the same method name , it would make things ambiguous for the compiler.The compiler won't know which method it should run.

To find out more see this question

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM