HomeiOS DevelopmentSwift command design sample - The.Swift.Dev.

Swift command design sample – The.Swift.Dev.



· 1 min learn


This time I’ll present you a behavioral sample. Here’s a little instance of the command design patten written in Swift.

The command sample may be helpful when you’d like to supply a typical interface for various actions that will probably be executed later in time. Normally it’s 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 see 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().data()
    }
}

class Assist {

    func data() {
        print("""

             🤖 Commander 🤖
                  v1.0

        Out there instructions:

            👉 assist      This command
            👉 ls        Record paperwork

        Bye! 👋

        """)
    }
}

class ListCommand: Command {

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

class Record {

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

For those who save this file, can run it by merely typing ./file-name.swift from a terminal window. The Swift compiler will deal with the remaining.

Actual world use circumstances for the command design sample:

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

As you possibly can see this sample may be utilized in a number of areas. Apple even made a particular class for this goal known as NSInvocation, however sadly it’s not out there in Swift, attributable to it’s dynamic habits. That’s not a giant deal, you possibly can at all times make your individual protocol & implementation, normally you simply want one further class that wraps the underlying command logic. 😛

Associated posts


· 2 min learn


Study concerning the initialization means of the 2 well-known courses in UIKit. Say whats up to UIViewcontroller, and UIView init patterns.


· 4 min learn


Study the iterator design sample by utilizing some customized sequences, conforming to the IteratorProtocol from the Swift commonplace library.


· 4 min learn


Learn to use lazy properties in Swift to enhance efficiency, keep away from optionals or simply to make the init course of extra clear.


· 1 min learn


Let’s mix manufacturing facility technique with easy manufacturing facility voilá: right here is the summary manufacturing facility design sample written in Swift language!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments