Swift command design sample – The.Swift.Dev.


The command sample will be useful if you would like to supply a typical interface for various actions that might 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() {
        Assist().information()
    }
}

class Assist {

    func information() {
        print("""

             🤖 Commander 🤖
                  v1.0

        Obtainable instructions:

            👉 assist      This command
            👉 ls        Listing paperwork

        Bye! 👋

        """)
    }
}

class ListCommand: Command {

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

class Listing {

    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()

In case you save this file, can run it by merely typing ./file-name.swift from a terminal window. The Swift compiler will maintain the remaining.

Actual world use circumstances for the command design sample:

  • varied button actions
    • assortment / desk view choice actions
    • navigating between controllers
    • historical past administration / undo supervisor
    • transactional habits
    • progress administration
    • wizards

As you may see this sample will be utilized in a number of areas. Apple even made a particular class for this function known as NSInvocation, however sadly it is not out there in Swift, resulting from it is dynamic habits. That is not an enormous deal, you may all the time make your individual protocol & implementation, usually you simply want one additional class that wraps the underlying command logic. 😛

Recent Articles

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here

Stay on op - Ge the daily news in your inbox