Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
71
Help us understand the problem. What is going on with this article?
@1024jp

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

More than 3 years have passed since last update.

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 { }
}

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

71
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
1024jp
🗣 Cocoa, Python, web, etc. / 🔧 開発中 macOS apps: 🖋 CotEditor, 👻 Gapplin, 🌊 BathyScaphe (共同)

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
71
Help us understand the problem. What is going on with this article?