LoginSignup
79
79

More than 5 years have passed since last update.

Swift でシングルトン

Last updated at Posted at 2014-06-04

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はわざわざ書く必要ないようです。

--
- cf. dispatch_once singleton model in swift -Stack Overflow

79
79
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
79
79