OSDN Git Service

staticプロパティをインスタンスプロパティに変更
[kcd/KCD.git] / KCD / ShipSlotObserver.swift
1 //
2 //  ShipSlotObserver.swift
3 //  KCD
4 //
5 //  Created by Hori,Masaki on 2017/12/31.
6 //  Copyright © 2017年 Hori,Masaki. All rights reserved.
7 //
8
9 import Cocoa
10
11 protocol ShipSlotObserverDelegate: class {
12     
13     func didChangeSlot0()
14     func didChangeSlot1()
15     func didChangeSlot2()
16     func didChangeSlot3()
17     func didChangeSlot4()
18 }
19
20 class ShipSlotObserver: NSObject {
21     
22     private enum SlotPosition {
23         
24         case first
25         
26         case second
27         
28         case third
29         
30         case fourth
31         
32         case fifth
33     }
34     
35     private let ship: Ship
36     
37     weak var delegate: ShipSlotObserverDelegate?
38     
39     private var observations: [NSKeyValueObservation] = []
40     
41     init(ship: Ship) {
42         
43         self.ship = ship
44         
45         super.init()
46         
47         observeSlot()
48         observeOnSlot()
49     }
50     
51     private func observeSlot() {
52         
53         let keyPaths = [\Ship.slot_0, \Ship.slot_1, \Ship.slot_2, \Ship.slot_3, \Ship.slot_4]
54         observe(keyPaths: keyPaths)
55     }
56     
57     private func observeOnSlot() {
58         
59         let keyPaths = [\Ship.onslot_0, \Ship.onslot_1, \Ship.onslot_2, \Ship.onslot_3, \Ship.onslot_4]
60         observe(keyPaths: keyPaths)
61     }
62     
63     private func observe(keyPaths: [KeyPath<Ship, Int>]) {
64         
65         let positions: [SlotPosition] = [.first, .second, .third, .fourth, .fifth]
66         
67         observations += zip(keyPaths, positions)
68             .map { [weak self] keyPath, position in
69                 
70                 ship.observe(keyPath) { _, _ in
71                     
72                     self?.notifyChange(on: position)
73                 }
74         }
75     }
76     
77     private func notifyChange(on position: SlotPosition) {
78         
79         switch position {
80             
81         case .first: delegate?.didChangeSlot0()
82             
83         case .second: delegate?.didChangeSlot1()
84             
85         case .third: delegate?.didChangeSlot2()
86             
87         case .fourth: delegate?.didChangeSlot3()
88             
89         case .fifth: delegate?.didChangeSlot4()
90             
91         }
92     }
93 }