Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //シングルトンとはクラスの作成を毎回行わないために行うもの
- //ここで使われているsharedManager → クラスの初期化はもう済ませています。何かしたい時は私からアクセスしてください。
- import UIKit
- class Manager {
- var pop:String
- var poppop:String
- //Managerクラスを作成しているのでinitは自動的に行われる
- //sharedManagerの中にinitが行われたManagerクラスが入っています。
- static let sharedManager = Manager()
- private init(pop0:String = "後で代入で変えます",pop1:String = "代入はしないでおきます") {
- //クラスが持っている変数にinitで得られる引数を渡す
- self.pop = pop0
- self.poppop = pop1
- }
- func hello(_ oo:String = "もしもし"){
- print(oo)
- print(pop)
- print(poppop)
- }
- }
- class ViewController: UIViewController {
- override func viewDidLoad() {
- super.viewDidLoad()
- // Do any additional setup after loading the view, typically from a nib.
- // クラスを呼ぶ時は初期化しますがinitがプライベートなので初期化してルものが入っているsharedManagerにアクセスします。
- let sample1 = Manager.sharedManager
- //initが行えないのでもう行ってあるものからhelloを呼び出す。
- //クラスの生成はinitがないと行えない。しかしプライベートで呼び出せない。
- sample1.hello("おはようございます")
- //おはようございます
- //後で代入で変えます
- //代入はしないでおきます
- sample1.hello("こんにちは")
- //こんにちは
- //後で代入で変えます
- //代入はしないでおきます
- sample1.hello("こんばんは")
- //こんばんは
- //後で代入で変えます
- //代入はしないでおきます
- //クラスの中にある変数を書き換えます。
- sample1.pop = "🐶"
- sample1.hello("わんわん")
- //わんわん
- //🐶
- //代入はしないでおきます
- //sharedManagerさえあれば呼び出せるので代入とかしないでの書き方。
- //上でクラスの変数の直接値を変えたので2行目は変わっています。
- Manager.sharedManager.hello("え?なんだって?")
- //え?なんだって?
- //🐶
- //代入はしないでおきます
- // エラーになります。 initはプライベートなものになっているので。
- // 直接呼び出せません。 だからもう初期化を済ましているsharedManagerが必要なのです。
- // let sample2 = Manager.init("aaa")
- // let sample3 = Manager()
- }
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
- // Dispose of any resources that can be recreated.
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement