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 {
35 private let ship: Ship
37 weak var delegate: ShipSlotObserverDelegate?
39 private var observations: [NSKeyValueObservation] = []
51 private func observeSlot() {
53 let keyPaths = [\Ship.slot_0, \Ship.slot_1, \Ship.slot_2, \Ship.slot_3, \Ship.slot_4]
54 observe(keyPaths: keyPaths)
57 private func observeOnSlot() {
59 let keyPaths = [\Ship.onslot_0, \Ship.onslot_1, \Ship.onslot_2, \Ship.onslot_3, \Ship.onslot_4]
60 observe(keyPaths: keyPaths)
63 private func observe(keyPaths: [KeyPath<Ship, Int>]) {
65 let positions: [SlotPosition] = [.first, .second, .third, .fourth, .fifth]
67 observations += zip(keyPaths, positions)
68 .map { [weak self] keyPath, position in
70 ship.observe(keyPath) { _, _ in
72 self?.notifyChange(on: position)
77 private func notifyChange(on position: SlotPosition) {
81 case .first: delegate?.didChangeSlot0()
83 case .second: delegate?.didChangeSlot1()
85 case .third: delegate?.didChangeSlot2()
87 case .fourth: delegate?.didChangeSlot3()
89 case .fifth: delegate?.didChangeSlot4()