swift 中 CommandLine.arguments 和 Processinfo.processinfo.arguments 之间的区别

Jun*_*hoi 4 command-line-arguments swift

我想知道如何将这些不同 的CommandLine ProcessInfo

let elements = CommandLine.arguments
let elements = Processinfo.processinfo.arguments
Run Code Online (Sandbox Code Playgroud)

在我看来,ProcessInfo 的论点具有命令行的所有概念。所以处理争论没有区别。

下面的代码使用 CommandLine.arguments,用于练习读写文件。

如果我将 Processinfo.processinfo.arguments 放在 CommanLine.arguments 的位置。没有改变。

static func makeInOutFile() -> (inputFile: String, outputFile: String)? {
    let elements = CommandLine.arguments
    let inputFile: String
    let outputFile: String
    switch elements.count {
    case 2:
        inputFile = elements[1]
        outputFile = Message.ofDefaultJSONFileName.description
        return (inputFile: inputFile, outputFile: outputFile)
    case 3:
        inputFile = elements[1]
        outputFile = elements[2]
        return (inputFile: inputFile, outputFile: outputFile)
    default:
        print (Message.ofFailedProcessingFile)
        return nil
    }
}
Run Code Online (Sandbox Code Playgroud)

rma*_*ddy 5

CommandLine 是 Swift 标准库的一部分,只提供命令行参数和参数计数。

ProcessInfo是 Foundation 框架的一部分(不是语言的一部分)。虽然ProcessInfo.arguments确实为您提供了与 相同的结果CommandLine.arguments,但ProcessInfo该类还有更多内容。

虽然两者arguments在功能上相同,但如果您只需要命令行参数,请使用CommandLine. 它更简单,它不依赖任何额外的框架,并且更易于移植到其他 Swift 运行时。