Mar*_*ams 293
更新01/17/17:更新了Swift 3的示例.Process已重命名为CommandLine.
2015年9月30日更新:更新了在Swift 2中工作的示例.
实际上,没有基金会或者 C_ARGV也可以这样做C_ARGC.
Swift标准库包含一个结构CommandLine,该结构具有一个String被调用的s 集合arguments.所以你可以打开这样的参数:
for argument in CommandLine.arguments {
switch argument {
case "arg1":
print("first argument")
case "arg2":
print("second argument")
default:
print("an argument")
}
}
Run Code Online (Sandbox Code Playgroud)
Mac*_*nik 55
在Swift 3中使用CommandLineenum而不是Process
所以:
let arguments = CommandLine.arguments
Run Code Online (Sandbox Code Playgroud)
orj*_*orj 44
使用顶级常量C_ARGC和C_ARGV.
for i in 1..C_ARGC {
let index = Int(i);
let arg = String.fromCString(C_ARGV[index])
switch arg {
case "this":
println("this yo");
case "that":
println("that yo")
default:
println("dunno bro")
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我使用的范围是1..C_ARGC因为C_ARGV"数组" 的第一个元素是应用程序的路径.
该C_ARGV变量实际上不是一个数组,但可以像数组一样进行子脚本编写.
Mic*_*ata 13
任何想要使用旧的"getopt"(可在Swift中使用)的人都可以使用它作为参考.我在C中创建了一个GNU示例的Swift端口,可以找到:
http://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.html
有完整的描述.它经过测试,功能齐全.它也不需要基金会.
var aFlag = 0
var bFlag = 0
var cValue = String()
let pattern = "abc:"
var buffer = Array(pattern.utf8).map { Int8($0) }
while true {
let option = Int(getopt(C_ARGC, C_ARGV, buffer))
if option == -1 {
break
}
switch "\(UnicodeScalar(option))"
{
case "a":
aFlag = 1
println("Option -a")
case "b":
bFlag = 1
println("Option -b")
case "c":
cValue = String.fromCString(optarg)!
println("Option -c \(cValue)")
case "?":
let charOption = "\(UnicodeScalar(Int(optopt)))"
if charOption == "c" {
println("Option '\(charOption)' requires an argument.")
} else {
println("Unknown option '\(charOption)'.")
}
exit(1)
default:
abort()
}
}
println("aflag ='\(aFlag)', bflag = '\(bFlag)' cvalue = '\(cValue)'")
for index in optind..<C_ARGC {
println("Non-option argument '\(String.fromCString(C_ARGV[Int(index)])!)'")
}
Run Code Online (Sandbox Code Playgroud)
小智 11
您可以使用CommandLine.arguments数组创建参数解析器并添加您喜欢的任何逻辑。
你可以测试一下。创建文件arguments.swift
//Remember the first argument is the name of the executable\nprint("you passed \\(CommandLine.arguments.count - 1) argument(s)")\nprint("And they are")\nfor argument in CommandLine.arguments {\n print(argument)\n}\nRun Code Online (Sandbox Code Playgroud)\n编译并运行它:
\n$ swiftc arguments.swift\n$ ./arguments argument1 argument2 argument3\nRun Code Online (Sandbox Code Playgroud)\n构建自己的参数解析器的问题是考虑所有命令行参数约定。我建议使用现有的参数解析器。
\n你可以使用:
\n我写过关于如何在这三个平台上构建命令行工具的文章。您应该检查它们并决定哪种风格最适合您。
\n如果您有兴趣,这里有链接:
\nApple 已经发布了ArgumentParser用于执行此操作的库:
我们很高兴地宣布
ArgumentParser,这是一个新的开源库,它使它变得简单——甚至令人愉快!— 在 Swift 中解析命令行参数。
https://github.com/apple/swift-argument-parser
首先声明一个类型,该类型定义您需要从命令行收集的信息。使用
ArgumentParser的属性包装器之一装饰每个存储的属性,并声明符合ParsableCommand.该
ArgumentParser库解析命令行参数,实例化您的命令类型,然后执行您的自定义run()方法或退出并显示有用的消息。
| 归档时间: |
|
| 查看次数: |
35197 次 |
| 最近记录: |