LoginSignup
49
47

More than 5 years have passed since last update.

Singletonを作るときに重要な、static変数とclass変数の違い in Swift

Posted at

swift1.2ではクラスのタイプメソッドとしてstatic変数が導入された。これは、構造体や列挙型でのstaticと同様に振る舞う。

シングルトンパターン

このstaticによって、swiftでシングルトンパターンを記述するのがとても簡単になった。

class SingletonA {
    static let sharedInstance = SingletonA()
    # do the job
}

swift1.2以前では、以下のように記述する必要があった。上記の方法と比べると、非常に冗長である。

class SingletonB {
    class var sharedInstance: SingletonB {
        struct Static {
            static let instance: SingletonB = SingletonB()
        }
        return Static.instance
    }
    # do the job
}

swift1.2最高という気持ちしかない。
ただ、なぜclass let sharedInstance = SingletonA()ではいけないのだろうか。

違い

重要な違いは static変数は一度しかサブクラスはoverrideできず、class変数はそれができてしまうということっぽい。

classをつかってclass let sharedInstance = SingletonA()とすると、誤ってサブクラスで上書きしてしまい、アプリ全体に1つしかあるべきでないオブジェクトが複数できてしまう可能性がある。

だからclass変数しか使えなかった以前のクラスでは、内部に構造体をつくることで無理やりstaticを作っているのだと理解している。

49
47
2

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
49
47