December 2018
Intermediate to advanced
414 pages
10h 19m
English
First, let's see how this reader could look if we implement its state with an enum:
class CardReader {
Implement the state with the enum, with all the possible state values, as follows:
enum State { case unknown case waiting case reading case read(CardInfo) case failed(Error)}
Use the private var state property so that no one can mutate the state from outside:
private var state: State = .unknown
The main routine is implemented as follows. For each loop, it will print the current state:
func start() { while true { print("\(state)") switch state { case .unknown: state = .waiting case .waiting:
When we're waiting, we wait for a card to be detected by the radio. When the card is detected, we change the state to reading:
if seenCard() ...Read now
Unlock full access