Swift equivalent of [NSBundle bundleForClass:[self class]]

Swift

Swift 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)
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDanilView Question on Stackoverflow
Solution 1 - SwiftAntonioView Answer on Stackoverflow
Solution 2 - SwiftAliaksandr BialiauskiView Answer on Stackoverflow
Solution 3 - SwiftOleh KudinovView Answer on Stackoverflow
Solution 4 - SwiftSakiboyView Answer on Stackoverflow
Solution 5 - SwiftMark SemselView Answer on Stackoverflow
Solution 6 - SwiftWilliam HuView Answer on Stackoverflow
Solution 7 - SwiftSiegfoultView Answer on Stackoverflow
Solution 8 - SwiftAyAzView Answer on Stackoverflow
Solution 9 - SwiftInitialCView Answer on Stackoverflow