I want to use the singleton pattern in my class which has a private init
with parameter. It also has a class function called setup
which configures and creates the shared instance. My objective-c code would be:
@interface MySingleton: NSObject
+ (MySingleton *)setup:(MyConfig *)config;
+ (MySingleton *)shared;
@property (readonly, strong, nonatomic) MyConfig *config;
@end
@implementation MySingleton
static MySingleton *sharedInstance = nil;
+ (MySingleton *)setup:(MyConfig *)config {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] initWithConfig:config];
});
// Some other stuff here
return sharedInstance;
}
+ (MySingleton *)shared {
if (sharedInstance == nil) {
NSLog(@"error: shared called before setup");
}
return sharedInstance;
}
- (instancetype)initWithConfig:(RVConfig *)config {
self = [super init];
if (self) {
_config = config;
}
return self;
}
@end
I am stuck with Swift:
class Asteroid {
var config: ASTConfig? // This actually should be read-only
class func setup(config: ASTConfig) -> Asteroid {
struct Static {
static let instance : Asteroid = Asteroid(config: config)
}
return Static.instance
}
class var shared: Asteroid? {
// ???
}
private init(config: ASTConfig) {
self.config = config
}
}
I think I am still thinking in objective-c way and couldn't figure it out with swift. Any help?