2 // ShipSlotObserver.swift
5 // Created by Hori,Masaki on 2017/12/31.
6 // Copyright © 2017年 Hori,Masaki. All rights reserved.
11 protocol ShipSlotObserverDelegate: class {
20 class ShipSlotObserver: NSObject {
22 private enum SlotPosition {
30 private let ship: Ship
32 weak var delegate: ShipSlotObserverDelegate?
34 private var observations: [NSKeyValueObservation] = []
46 private func observeSlot() {
48 let keyPaths = [\Ship.slot_0, \Ship.slot_1, \Ship.slot_2, \Ship.slot_3, \Ship.slot_4]
49 observe(keyPaths: keyPaths)
52 private func observeOnSlot() {
54 let keyPaths = [\Ship.onslot_0, \Ship.onslot_1, \Ship.onslot_2, \Ship.onslot_3, \Ship.onslot_4]
55 observe(keyPaths: keyPaths)
58 private func observe(keyPaths: [KeyPath<Ship, Int>]) {
60 let positions: [SlotPosition] = [.first, .second, .third, .fourth, .fifth]
62 observations += zip(keyPaths, positions)
63 .map { [weak self] keyPath, position in
64 ship.observe(keyPath) { _, _ in
65 self?.notifyChange(on: position)
70 private func notifyChange(on position: SlotPosition) {
74 case .first: delegate?.didChangeSlot0()
75 case .second: delegate?.didChangeSlot1()
76 case .third: delegate?.didChangeSlot2()
77 case .fourth: delegate?.didChangeSlot3()
78 case .fifth: delegate?.didChangeSlot4()