London Escorts sunderland escorts 1v1.lol unblocked yohoho 76 https://www.symbaloo.com/mix/yohoho?lang=EN yohoho https://www.symbaloo.com/mix/agariounblockedpvp https://yohoho-io.app/ https://www.symbaloo.com/mix/agariounblockedschool1?lang=EN
2.2 C
New York
Saturday, February 1, 2025

Tips on how to construct higher command line apps and instruments utilizing Swift?


Operating Swift recordsdata as scripts

It’s attainable to run a Swift file straight from the command line if you happen to add a hashbang) to the start of the file. This manner you do not have to manually compile the code utilizing the swiftc command. You may merely give the file the executable permission flag and the system will name the Swift REPL below the hood, so our app could be evaluated mechanically. ?

#!/usr/bin/env swift

print("Whats up, world!")

For instance this important.swift file above could be marked as an executable file, and we will merely name it by way of the ./important.swift command afterward (you simply have to make use of chmod just one time).

chmod +x important.swift 
./important.swift  
# Whats up, world!

The great thing about this technique is that you would be able to quickly check your Swift command line snippets. You may even place the completed Swift scripts below the /usr/native/bin/ listing with out the swift file extension to make them accessible “globally” on your working system person. ?

Utilizing command line arguments in Swift

The CommandLine enum makes it very simple to fetch the arguments handed to our Swift utility or script. You may entry each argument utilizing the arguments variable as an array of Strings, however additionally it is attainable to get the uncooked information utilizing the argc and unsafeArgv properties.

#!/usr/bin/env swift


let script = CommandLine.arguments[0]
print("Script:", script)


let inputArgs = CommandLine.arguments.dropFirst()
print("Variety of arguments:", inputArgs.depend)

print("Arguments:")
for arg in inputArgs {
    print("-", arg)
}

You must notice that the primary argument is at all times the trail of the present script, so if you’re solely searching for the enter arguments you should use the dropFirst() technique to return a subset of the enter strings. Normally every argument is separated by an area character.

./important.swift hey world
# Script: important.swift
# Variety of arguments: 2
# Arguments:
# - hey
# - world

In Xcode you’ll be able to add customized arguments below the Edit Scheme… menu merchandise while you click on on the present scheme, search for the Arguments tab and use the Arguments Handed On Launch part.

Course of data and atmosphere in Swift Similar to we will entry command line arguments, it’s attainable to look at the present course of together with some {hardware} data and atmosphere variables.

#!/usr/bin/env swift
import Basis

let data = ProcessInfo.processInfo

print("Course of data")
print("Course of identifier:", data.processIdentifier)
print("System uptime:", data.systemUptime)
print("Globally distinctive course of id string:", data.globallyUniqueString)
print("Course of title:", data.processName)

print("Software program data")
print("Host title:", data.hostName)
print("OS main model:", data.operatingSystemVersion.majorVersion)
print("OS model string", data.operatingSystemVersionString)

print("{Hardware} data")
print("Lively processor depend:", data.activeProcessorCount)
print("Bodily reminiscence (bytes)", data.physicalMemory)


print("Arguments")
print(ProcessInfo.processInfo.arguments)

print("Surroundings")

print(data.atmosphere)

The atmosphere variables property is a Dictionary the place each the keys and the values can be found as strings, so that you may need to parse them if you’re searching for totally different worth sorts. You may arrange atmosphere customized variables in Xcode identical to arguments, or you’ll be able to go them by way of the command line earlier than you execute the Swift script utilizing the export command.

Commonplace enter and output in Swift

You should utilize the print operate to jot down textual content to the usual output, however it is best to notice that the print operate has a variadic gadgets definition, so you’ll be able to go round a number of arguments and a customized separator & terminator parameter to show extra superior outputs.

There’s additionally a typical error stream, which is a part of the normal streams after all, however what’s fascinating about it’s that you would be able to additionally write to this channel by means of the FileHandle.standardError property there’s fairly a chic resolution on a Stack Overflow thread initially created by Rob Napier, I’ll embody that one right here as nicely. ?

One other nice characteristic of the print operate is the to parameter, which may settle for a customized TextOutputStream so you’ll be able to wrap the stderr stream in a customized object or you can even create customized output handlers and separate your print statements e.g. by context if you happen to want.

#!/usr/bin/env swift
import Basis


print("This", "is", "enjoyable", separator: "-", terminator: "!")


"This goes to the usual error output"
    .information(utilizing: .utf8)
    .map(FileHandle.standardError.write)


remaining class StandardErrorOutputStream: TextOutputStream {
    func write(_ string: String) {
        FileHandle.standardError.write(Information(string.utf8))
    }
}

var outputStream = StandardErrorOutputStream()
print("That is additionally an error", to: &outputStream)



func clear() {
    print("u{1B}[2J")
    print("u{1B}[(1);(0)H", terminator: "")
}

print("foooooooooooooooooooooo")
clear()
print("Hello, world!")



print("u{1b}[31;1mu{1b}[40;1m("Hello, world!")u{1b}[m")
print("u{1b}[32;1m("Hello, world!")u{1b}[m")


print("Please enter your input:")
guard let input = readLine(strippingNewline: true) else {
    fatalError("Missing input")
}
print(input)

The second half of the snippet is full of ANSI escape codes which I like quite a lot, because it can make our terminal output quite beautiful. The only problem is that they don’t work in Xcode at all (come-on Apple, please support this…). You can clear the console or change the background / foreground color of the output by using these codes.

There are quite a lot of libraries on GitHub that you can use to print colorful output, for example ColorizeSwift, ANSITerminal, ANSIEscapeCode and many more cool ones.

The very last thing that I’d like to show you is the readLine function, which you can use to read a line from the standard input. This comes handy if you need to get user input from the command line.

Use an argument parser library

If you are looking for a type-safe argument parser written in Swift, you should definitely take a look at the Swift Argument Parser library. It is created and maintained by Apple, so it’s kind of an official solution for this particular issue, but IMHO it lacks some advanced features.

This is the main reason why I prefer the Vapor command API built on top of the ConsoleKit library. Both libraries can parse arguments, options and flags, but ConsoleKit is also capable of displaying progress indicators, it features multiple command groups, secure input, auto-completion, multiple log levels and many more.


import Foundation
import ConsoleKit

final class HelloCommand: Command {
        
    struct Signature: CommandSignature {

        @Argument(name: "name", help: "The name to say hello")
        var name: String

        @Option(name: "greeting", short: "g", help: "Greeting used")
        var greeting: String?

        @Flag(name: "capitalize", short: "c", help: "Capitalizes the name")
        var capitalize: Bool
    }

    static var name = "hello"
    let help = "This command will say hello to a given name."

    func run(using context: CommandContext, signature: Signature) throws {
        let greeting = signature.greeting ?? "Hello"
        var name = signature.name
        if signature.capitalize {
            name = name.capitalized
        }
        print("(greeting) (name)!")
        
        
        let bar = context.console.progressBar(title: "Hello")
        bar.start()
        
        bar.succeed()
        
        
        let foo = context.console.ask("What?")
        print(foo)
        
        
        let baz = context.console.ask("Secure what?", isSecure: true)
        print(baz)
        
        
        let c = context.console.choose("Make a choice", from: ["foo", "bar", "baz"])
        print(c)

        
    }
}


import Basis
import ConsoleKit

let console: Console = Terminal()
var enter = CommandInput(arguments: CommandLine.arguments)
var context = CommandContext(console: console, enter: enter)

var instructions = Instructions(enableAutocomplete: true)
instructions.use(HelloCommand(), as: HelloCommand.title, isDefault: false)

do {
    let group = instructions.group(assist: "Utilizing ConsoleKit with out Vapor.")
    strive console.run(group, enter: enter)
}
catch {
    console.error("(error)")
    exit(1)
}

You should utilize each resolution by means of the Swift Package deal Supervisor, the setup course of is kind of simple, you may discover extra tutorials concerning the Swift Argument Parser and I believe that it’s tougher to seek out correct docs for ConsoleKit, so yeah… anyway, they’re nice libraries you will not remorse utilizing them. ?

Benefit from the Swift Package deal Supervisor

The Swift Package deal Supervisor is among the neatest thing concerning the Swift programming language. I actually find it irresistible and I exploit it virtually on daily basis. The truth that the package deal manifest file is outlined utilizing Swift itself makes it simple to make use of & perceive.


import PackageDescription

let package deal = Package deal(
    title: "myProject",
    platforms: [
        .macOS(.v10_15)
    ],
    dependencies: [
        .package(url: "https://github.com/vapor/console-kit", from: "4.1.0"),
    ],
    targets: [
        .executableTarget(name: "myProject",dependencies: [
            .product(name: "ConsoleKit", package: "console-kit"),
        ]),
        .testTarget(title: "myProjectTests", dependencies: ["myProject"]),
    ]
)

The package deal supervisor developed rather a lot throughout the previous few months, if you happen to check out the Swift Evolution dashboard you’ll be able to observe these modifications, the latest replace was the introduction of customized, user-defined Package deal Collections, however if you’re searching for packages you’ll be able to at all times check out the Swift Package deal Index web site. ?

Related Articles

Social Media Auto Publish Powered By : XYZScripts.com