This project is archived. I’m happy with how CLInterface turned out; it’s architecture includes extensive use of reflection to achieve exactly the API I wanted. Unfortunatly, soon after it’s release, Apple came out with its own first-party argument parser library that has a very similar interface.
Swift 5.1 era argument parser
CLInterface protocol should be implemented by a class or a struct that will represent command line interface of your program. Apart from required description property, it should contain @Argument and @PositionalArgument properties for any arguments you want. They will be set automatically after you call parseArguments.
Both optional and required arguments are supported. Use default: and optional properies to get the behavior you want. (For example, non-optional property without default value will throw error at parseArguments call.)
final class Swiftc : CLInterface {
var description = "Swift compiler"
@Argument("--output", "-o", usage: "Write output to <file>")
var outputPath: String?
@Argument("-g", usage: "Emit debug info", default: false)
var debugMode: Bool
@PositionalArgument(name: "files", usage: "Files that will be compiled")
var files: [String]
}
After calling parseArguments, you will be able to use these properties like normal variables.
OVERVIEW: Swift compiler
OPTIONS:
--output, -o Write output to <file>
-g Emit debug info
--help Display available options
POSITIONAL ARGUMENTS:
files Files that will be compiled
CLInterface
Swift 5.1 era argument parser
CLInterface
protocol should be implemented by a class or a struct that will represent command line interface of your program. Apart from requireddescription
property, it should contain@Argument
and@PositionalArgument
properties for any arguments you want. They will be set automatically after you callparseArguments
.Both optional and required arguments are supported. Use
default:
and optional properies to get the behavior you want. (For example, non-optional property without default value will throw error atparseArguments
call.)Use Swift package manager to add to your project:
Example
After calling
parseArguments
, you will be able to use these properties like normal variables.swiftc -h
orswiftc --help
prints usage info:See
ExampleSwiftc
for working example.See Opusab, my audiobook converter, for another real-life example.