In a some popular open source swift project. I noticed following approach used to load a file from main bundle.
@objc class TestClass: NSObject { }
let bun
This returns the bundle that contains the TestClass
class:
NSBundle(forClass: TestClass.self)
While this returns the main bundle of the application:
NSBundle.mainBundle()
If you execute this code from your application code, it will always return your main bundle. But if that class is contained in a different library or framework, it will return the bundle that contains it.
For example, all Swift libraries in CocoaPods are integrated using dynamic frameworks, and they are deployed in a different bundle inside the main bundle. So all the frameworks must use the embedded bundle to access their resources.
I'd recommend using the first approach (NSBundle(forClass:)
method) to improve code portability. And it's required when creating dynamic frameworks.