Swift command design sample – The.Swift.Dev.


The command sample could be helpful if you would like to offer a typical interface for various actions that can be executed later in time. Normally it is an object that encapsulates all the data wanted to run the underlying motion correctly.

Instructions are sometimes used to deal with consumer interface actions, create undo managers, or handle transactions. Let’s have a look at a command sample implementation in Swift by making a command line argument handler with emojis. ๐Ÿ’พ

#!/usr/bin/env swift

import Basis

protocol Command {
    func execute()
}

class HelpCommand: Command {

    func execute() {
        Assist().information()
    }
}

class Assist {

    func information() {
        print("""

             ๐Ÿค– Commander ๐Ÿค–
                  v1.0

        Accessible instructions:

            ๐Ÿ‘‰ assist      This command
            ๐Ÿ‘‰ ls        Checklist paperwork

        Bye! ๐Ÿ‘‹

        """)
    }
}

class ListCommand: Command {

    func execute() {
        Checklist().homeDirectoryContents()
    }
}

class Checklist {

    func homeDirectoryContents() {
        let fileManager = FileManager.default
        guard let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else {
            print("Couldn't open paperwork listing")
            exit(-1)
        }
        do {
            let fileURLs = strive fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
            print("nt๐Ÿ“ Itemizing paperwork listing:n")
            print(fileURLs.map { "tt๐Ÿ’พ " + $0.lastPathComponent }.joined(separator: "nn") + "n" )
        }
        catch {
            print(error.localizedDescription)
            exit(-1)
        }

    }
}

class App {

    var instructions: [String:Command] = [:]

    init() {
        self.instructions["help"] = HelpCommand()
        self.instructions["ls"] = ListCommand()
    }

    func run() {
        let arguments = CommandLine.arguments[1...]

        guard let key = arguments.first, self.instructions[key] != nil else "))]")
            exit(-1)
        

        self.instructions[key]!.execute()
    }
}

App().run()

When you save this file, can run it by merely typing ./file-name.swift from a terminal window. The Swift compiler will deal with the remainder. โš’