LoginSignup
72
70

More than 5 years have passed since last update.

Swift でシングルトン (Swift 1.2 以降版)

Last updated at Posted at 2015-04-16

Update: Swift 2.x, 3.0 においてもこの記法は有効です。

Swift 1.2 の改定でプロパティに static 修飾子が付けられるようになりました。
ということは、シングルトンパターンがもっと短く書けます。

今までこう書いていたのが...


class FooController: NSObject {

    // singleton in previous Swift
    class var sharedController : FooController {
        struct Singleton {
            static let instance = FooController()
        }
        return Singleton.instance
    }

    // ...
}

こうなる...!


class FooController {

    // singleton in Swift 1.2+
    static let shared = FooController()

    // ...
}

たった1行。

final 足して init をプライベートにするともっとシングルトン的かもね。


final class FooController {

    static let shared = FooController()

    private init { }
}

コードが短い、ステキー。

72
70
0

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
72
70