ric*_*ter 22
这里最好的解决方案取决于你需要捆绑的东西.
是否要查找仅存在于特定应用程序,框架或扩展包中的资源,这些资源在您编写的代码运行时已知会被加载?在这种情况下,您可能希望使用init(identifier:)
而不是动态查找定义特定类型的包.
注意"跟随类型"捆绑包查找.例如,如果框架类Foo
用于NSBundle(forClass: self.dynamicType)
加载资源,那么Foo
加载该框架的应用程序定义的子类将最终查找应用程序包而不是框架包.
如果确实需要对结构(或枚举)进行"跟随类型"捆绑查找,则可能有用的一种解决方法是将类定义为子类型:
struct Foo {
class Bar {}
static var fooBundle: NSBundle { return NSBundle(forClass: Foo.Bar.self) }
}
Run Code Online (Sandbox Code Playgroud)
注意这里没有动态,因为没有必要 - 每个Foo
都来自相同的类型定义(因为结构不能继承),所以它的静态类型匹配它的动态类型.
(不可否认,一个NSBundle(forType:)
可以处理结构,枚举和协议的东西可能会提出一个很好的功能请求.虽然我认为让它处理扩展和一切都可能很棘手......)
Val*_*nko 16
extension Bundle {
static var current: Bundle {
class __ { }
return Bundle(for: __.self)
}
}
Run Code Online (Sandbox Code Playgroud)
针对Swift 3.0+进行了更新:
struct Foo {
class Bar {}
static var fooBundle: Bundle { return Bundle(for: Foo.Bar.self) }
}
Run Code Online (Sandbox Code Playgroud)