Swift command design sample – The.Swift.Dev.

0/5 No votes

Report this app



The command sample could be useful if you would like to supply a standard interface for various actions that will likely be executed later in time. Often it is an object that encapsulates all the knowledge wanted to run the underlying motion correctly.

Instructions are sometimes used to deal with person interface actions, create undo managers, or handle transactions. Let’s examine 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() {

class Assist {

    func data() {

             ๐Ÿค– Commander ๐Ÿค–

        Out there instructions:

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

        Bye! ๐Ÿ‘‹


class ListCommand: Command {

    func execute() {

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")
        do {
            let fileURLs = attempt fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
            print("nt๐Ÿ“ Itemizing paperwork listing:n")
            print(fileURLs.map { "tt๐Ÿ’พ " + $0.lastPathComponent }.joined(separator: "nn") + "n" )
        catch {


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 "))]")



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


Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.