我想将这段代码转换成 Swift。这里的 Objective-C 代码正在创建一个单例对象(如果我可以这样描述的话)。我可以使用 dispatch_once_t 来转换它,但我想使用一种更优雅的方式,应该类似于“static let bundle: NSBundle!”。但是“static let bundle: NSBundle!”在扩展中是不允许的,因为它不允许存储属性。
那么是否可以不用dispatch_once_t来转换代码呢?
我遇到了一个问题,我不能在类扩展中存储属性
@implementation NSBundle (CTFeedback)
+ (NSBundle *)feedbackBundle
{
static NSBundle *bundle = nil;
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
NSBundle *classBundle = [NSBundle bundleForClass:[CTFeedbackViewController class]];
NSURL *bundleURL = [classBundle URLForResource:@"CTFeedback" withExtension:@"bundle"];
if (bundleURL) {
bundle = [NSBundle bundleWithURL:bundleURL];
} else {
bundle = [NSBundle mainBundle];
}
});
return bundle;
}
@end
我的 Swift 代码:
extension NSBundle
{
static func feedbackBundle()-> NSBundle
{
static let bundle: NSBundle! //!! **Compiler Error here**
let classBundle = NSBundle.init(forClass: CTFeedbackViewController.self)
let bundleURL = classBundle.URLForResource("CTFeedback", withExtension: "bundle")
if let bundleURL2 = bundleURL
{
bundle = NSBundle(URL: bundleURL2)
}
else
{
bundle = NSBundle.mainBundle()
}
return bundle;
}
}
更新:
感谢大家的回答。我现在就是这样做的。我不确定这是最好的方法/
private class FeedbackBundle
{
static let classBundle = NSBundle.init(forClass: CTFeedbackViewController.self)
}
extension NSBundle
{
static func feedbackBundle()-> NSBundle
{
let bundleURL = FeedbackBundle.classBundle.URLForResource("CTFeedback", withExtension: "bundle")
if let bundleURL2 = bundleURL
{
return NSBundle(URL: bundleURL2)!
}
else
{
return NSBundle.mainBundle()
}
}
}
最佳答案
在 Swift 中,您不能在扩展中添加静态变量。 如果可以的话,您可以在原来的类(class)重试。否则,您可以像这样修改代码:
if let bundleURL2 = bundleURL
{
return NSBundle(URL: bundleURL2)
}
else
{
return NSBundle.mainBundle()
}
关于ios - 如何在类扩展中添加静态(存储)属性以创建单例? ( swift ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38863358/