How do you access command line arguments in Swift?

前端 未结 6 1746
野趣味
野趣味 2020-12-04 07:02

How do you access command line arguments for a command line application in Swift?

6条回答
  •  一向
    一向 (楼主)
    2020-12-04 07:27

    You could create an argument parser by using the CommandLine.arguments Array and add any logic you like.

    You can test it. Create a file arguments.swift

    //Remember the first argument is the name of the executable
    print("you passed \(CommandLine.arguments.count - 1) argument(s)")
    print("And they are")
    for argument in CommandLine.arguments {
        print(argument)
    }
    

    compile it and run it:

    $ swiftc arguments.swift
    $ ./arguments argument1 argument2 argument3
    

    The issue with you building your own argument parser is taking into account all the command-line argument conventions. I would recommend using an existing Argument Parser.

    You could use:

    • Vapor's Console module
    • TSCUtility Argument Parser used by the Swift Package manager
    • The Swift Argument Parser open-sourced by Apple

    I've written about how to build command-line tools on all three. You should check them out and decide what style suits you best.

    If you are interested here are the links:

    •  Building a CLI tool using Swift and Vapor's Console module 
    • Command-line argument parsing using Swift Package Manager's TSCUtility module 
    • Understanding the Swift Argument Parser and working with STDIN

提交回复
热议问题