Skip to content

Instantly share code, notes, and snippets.

@alexathylane
Last active August 23, 2023 01:03
Show Gist options
  • Save alexathylane/f21be56dc146d281f55264c07b78134f to your computer and use it in GitHub Desktop.
Save alexathylane/f21be56dc146d281f55264c07b78134f to your computer and use it in GitHub Desktop.
A groundbreaking journal app
import Foundation
let fileManager = FileManager.default
let filePathURL = URL(fileURLWithPath: fileManager.currentDirectoryPath)
func safeReadLine(prompt: String) -> String {
print(prompt)
if let input = readLine() {
let sanitizedInput = input.trimmingCharacters(in: .whitespacesAndNewlines)
if !sanitizedInput.isEmpty && sanitizedInput != "" {
return input
}
}
print("Input cannot be empty. Please try again.")
return safeReadLine(prompt: prompt)
}
func createJournalEntry() {
let titlePrompt = "Enter the title of your journal entry:"
let title = safeReadLine(prompt: titlePrompt)
let fileName = "\(title.replacingOccurrences(of: " ", with: "_")).txt"
let filePath = filePathURL.appendingPathComponent(fileName)
if fileManager.fileExists(atPath: filePath.path) {
print("A journal entry with that title already exists. Try a different title.")
createJournalEntry()
}
let bodyPrompt = "Enter the body of your journal entry:"
let body = safeReadLine(prompt: bodyPrompt)
let content = "\(title)\n\n\(body)"
do {
try content.write(to: filePath, atomically: true, encoding: .utf8)
print("Journal entry saved!")
} catch {
print("Failed to save the journal entry. Error: \(error)")
}
}
func listJournalEntries() {
let enumerator = fileManager.enumerator(at: filePathURL, includingPropertiesForKeys: nil)
print("\nJournal entries:")
while let file = enumerator?.nextObject() as? URL {
if file.pathExtension == "txt" {
print("- \(file.lastPathComponent)")
}
}
}
func appLoop() {
while true {
let commandPrompt =
"""
\nPlease enter a command:
- Create a new journal entry ("create" or "c")
- List all journal entires ("list" or "l")
- Exit the app ("exit" or "e")
"""
let response = safeReadLine(prompt: commandPrompt).lowercased()
switch response {
case "create", "c":
createJournalEntry()
case "list", "l":
listJournalEntries()
case "exit", "e":
return
default:
print("Command not recognized.")
break
}
}
}
print("✨ Welcome to Journal3000! ✨")
appLoop()
print("Exiting Journal3000. Goodbye!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment