LoginSignup
2
2

More than 3 years have passed since last update.

【Swift】シングルトンを1分で理解する

Posted at

シングルトンとは

初期化処理を内部に梱包することで、外部から初期化しないようにし、
データを保持することのできる記法。
タスクキルしない限りデータを保持し続ける。
破棄(再初期化)されないので画面遷移してもデータが保持される。
言い換えればタスクキルでデータは消えるので
ローカルにデータを保存したい場合は、使えない。

class Singleton {
    var name:String = ""
    //内部に梱包>>
    static let shared = Singleton()
    private init() { //何も初期化しない
    }
    //<<
}

使い方

print(Singleton.shared.name) //""
Singleton.shared.name = "hoge"
print(Singleton.shared.name) //"hoge"
//...画面遷移
print(Singleton.shared.name) //"hoge"
2
2
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
2
2