Swift 1.2 からはもっと簡単に書けるようになりました。 (2015-04-17)
dispatch_once を使ったシングルトンクラスを Swift に移植する。
static の初期化は dispatch_once を勝手にやってくれるようです。
コードが短い、ステキー。
class var sharedController : FooController
{
struct Singleton {
static let instance = FooController()
}
return Singleton.instance
}
相当する Objective-C のコード。
+ (FooController *)sharedController
{
static dispatch_once_t token;
static FooController *instance = nil;
dispatch_once(&token, ^{
instance = [[FooController alloc] init];
});
return instance;
}
追記: @takabosoft さん @hetima さんのツッコミを受けて、Swiftのシングルトンコードを簡略化しました。dispatch_onceはわざわざ書く必要ないようです。
--