Advertisement
Guest User

Untitled

a guest
Mar 26th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.96 KB | None | 0 0
  1. //シングルトンとはクラスの作成を毎回行わないために行うもの
  2.  
  3. //ここで使われているsharedManager → クラスの初期化はもう済ませています。何かしたい時は私からアクセスしてください。
  4.  
  5. import UIKit
  6.  
  7. class Manager {
  8.  
  9. var pop:String
  10. var poppop:String
  11.  
  12. //Managerクラスを作成しているのでinitは自動的に行われる
  13. //sharedManagerの中にinitが行われたManagerクラスが入っています。
  14. static let sharedManager = Manager()
  15. private init(pop0:String = "後で代入で変えます",pop1:String = "代入はしないでおきます") {
  16. //クラスが持っている変数にinitで得られる引数を渡す
  17. self.pop = pop0
  18. self.poppop = pop1
  19. }
  20.  
  21. func hello(_ oo:String = "もしもし"){
  22. print(oo)
  23. print(pop)
  24. print(poppop)
  25. }
  26.  
  27. }
  28.  
  29. class ViewController: UIViewController {
  30.  
  31. override func viewDidLoad() {
  32. super.viewDidLoad()
  33. // Do any additional setup after loading the view, typically from a nib.
  34.  
  35. // クラスを呼ぶ時は初期化しますがinitがプライベートなので初期化してルものが入っているsharedManagerにアクセスします。
  36. let sample1 = Manager.sharedManager
  37.  
  38. //initが行えないのでもう行ってあるものからhelloを呼び出す。
  39. //クラスの生成はinitがないと行えない。しかしプライベートで呼び出せない。
  40.  
  41. sample1.hello("おはようございます")
  42. //おはようございます
  43. //後で代入で変えます
  44. //代入はしないでおきます
  45.  
  46. sample1.hello("こんにちは")
  47. //こんにちは
  48. //後で代入で変えます
  49. //代入はしないでおきます
  50.  
  51. sample1.hello("こんばんは")
  52. //こんばんは
  53. //後で代入で変えます
  54. //代入はしないでおきます
  55.  
  56. //クラスの中にある変数を書き換えます。
  57. sample1.pop = "🐶"
  58.  
  59. sample1.hello("わんわん")
  60. //わんわん
  61. //🐶
  62. //代入はしないでおきます
  63.  
  64.  
  65. //sharedManagerさえあれば呼び出せるので代入とかしないでの書き方。
  66. //上でクラスの変数の直接値を変えたので2行目は変わっています。
  67. Manager.sharedManager.hello("え?なんだって?")
  68. //え?なんだって?
  69. //🐶
  70. //代入はしないでおきます
  71.  
  72.  
  73. // エラーになります。 initはプライベートなものになっているので。
  74. //   直接呼び出せません。 だからもう初期化を済ましているsharedManagerが必要なのです。
  75. // let sample2 = Manager.init("aaa")
  76. // let sample3 = Manager()
  77.  
  78.  
  79.  
  80. }
  81.  
  82. override func didReceiveMemoryWarning() {
  83. super.didReceiveMemoryWarning()
  84. // Dispose of any resources that can be recreated.
  85. }
  86.  
  87.  
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement