Skip to content

Instantly share code, notes, and snippets.

@betopompolo
Last active August 3, 2024 02:17
Show Gist options
  • Select an option

  • Save betopompolo/18a4d0f512d276a135b38b1b4775c571 to your computer and use it in GitHub Desktop.

Select an option

Save betopompolo/18a4d0f512d276a135b38b1b4775c571 to your computer and use it in GitHub Desktop.
Terminal wrapper for ShoppingList demo
//
// Terminal.swift
//
//
// Created by Adalberto Nassu Pompolo on 18/07/24.
//
import Foundation
class Terminal {
static let divider = "----------"
static let help = """
\(Terminal.divider)
Lista de compras 🛒
- add: Adiciona um produto. Ex: add:pao
- remove: Remove um produto um produto. Ex: remove:pao
- search: Busca por um produto na lista. Ex: search:pao
- print: Mostra a lista. Ex: print
- quit: Sair do programa
\(Terminal.divider)
"""
static func run(onCommand: (_ command: Command) -> Bool) {
while(true) {
guard let input = readLine() else {
continue
}
guard let command = toCommand(input: input) else {
print(Terminal.help)
continue
}
if !onCommand(command) {
break
}
}
}
static private func toCommand(input: String) -> Command? {
if input == "print" {
return .print
}
if input == "quit" {
return .quit
}
let split = input.components(separatedBy: ":")
guard split.count == 2 else {
return nil
}
let (command, payload) = (split[0], split[1])
switch command {
case "add":
return .add(product: payload)
case "remove":
return .remove(product: payload)
case "search":
return .search(input: payload)
default:
return nil
}
}
enum Command {
case add(product: String)
case remove(product: String)
case search(input: String)
case print
case quit
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment