· 1 min learn
This time I will present you a behavioral sample. Here’s a little instance of the command design patten written in Swift.
The command sample could be useful in case you’d like to supply a standard 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
print("Utilization: ./command.swift [(self.commands.keys.joined(separator: "
class HelpCommand: Command "))]")
exit(-1)
class Assist {
func information()
print("Utilization: ./command.swift [(self.commands.keys.joined(separator: "
}
class ListCommand: Command {
func execute() {
List().homeDirectoryContents()
}
}
class List {
func homeDirectoryContents() {
let fileManager = FileManager.default
guard let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else {
print("Could not open documents directory")
exit(-1)
}
do {
let fileURLs = try fileManager.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: nil)
print("nt📁 Listing documents directory:n")
print(fileURLs.map { "tt💾 " + $0.lastPathComponent }.joined(separator: "nn") + "n" )
}
catch {
print(error.localizedDescription)
exit(-1)
}
}
}
class App {
var commands: [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 handle the remainder.
Actual world use instances for the command design sample:
+ numerous button actions
+ assortment / desk view choice actions
+ navigating between controllers
+ historical past administration / undo supervisor
+ transactional conduct
+ progress administration
+ wizards
As you may see this sample could be utilized in a number of areas. Apple even made a particular class for this function referred to as NSInvocation, however sadly it’s not obtainable in Swift, as a consequence of it’s dynamic conduct. That’s not an enormous deal, you may at all times make your personal protocol & implementation, typically you simply want one further class that wraps the underlying command logic. 😛
Associated posts
· 5 min learn
On this article I’m going to indicate you tips on how to implement a primary occasion processing system to your modular Swift software.
· 4 min learn
Be taught the iterator design sample by utilizing some customized sequences, conforming to the IteratorProtocol from the Swift normal library.
· 4 min learn
Discover ways to use lazy properties in Swift to enhance efficiency, keep away from optionals or simply to make the init course of extra clear.
· 5 min learn
Newbie’s information about optics in Swift. Discover ways to use lenses and prisms to control objects utilizing a useful method.

