Swift equivalent of [NSBundle bundleForClass:[self class]]
SwiftSwift Problem Overview
What is swift equivalent of next code:
[NSBundle bundleForClass:[self class]]
I need load resources from test bundle (JSON data)
Swift Solutions
Solution 1 - Swift
Never used, but I think it should be this:
Swift <= 2.x
NSBundle(forClass: self.dynamicType)
Swift 3.x
Bundle(for: type(of: self))
Solution 2 - Swift
Swift 3:
Bundle(for: type(of: self))
Solution 3 - Swift
Swift 5
Bundle(for: Self.self)
Solution 4 - Swift
I personally like:
let bun = NSBundle(forClass: self.classForCoder)
Solution 5 - Swift
let bundle = NSBundle(forClass:object_getClass(self))
Solution 6 - Swift
If you are working on a class then
Bundle(for: type(of: self))
Sometimes you may work in a struct, then you need to use any class in the bundle
Bundle(for: AnyClassInTheBundle.self)
Solution 7 - Swift
The selected answer did not work for me in a static method of a UIView subclass, but I found this:
Bundle(for: self.classForCoder)
This also works when you want to get the Bundle
within a test target.
Solution 8 - Swift
Loading the xib for dynamicType of the class
let bundle = NSBundle(forClass: self.dynamicType)
let nib = UINib(nibName: "CellForAlert", bundle: bundle)
let view = nib.instantiateWithOwner(self, options: nil).first as! UIView
view.frame = bounds
view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
self.addSubview(view);
Solution 9 - Swift
In Swift 3.0, you can use:
func kZWGetBundle() -> Bundle{
return Bundle(for: AnyClass.self as! AnyClass)
}