在Swift 3中,如何将getopt与命令行参数一起使用?
我试图在Swift 3中使用带有命令行参数的getopt。我来自: 当我使用此代码时:在Swift 3中,如何将getopt与命令行参数一起使用?,swift,command-line,swift3,Swift,Command Line,Swift3,我试图在Swift 3中使用带有命令行参数的getopt。我来自: 当我使用此代码时: let option = Int( getopt( CommandLine.argc, CommandLine.arguments, buffer ) ) 我得到这个错误: 无法将“[String]”类型的值转换为预期的参数类型 “不安全的指针!” 对于CommandLine.arguments,我尝试将其用作argv。有人知道getopt的第二个参数的正确语法吗?提前谢谢 CommandLine.argu
let option = Int( getopt( CommandLine.argc, CommandLine.arguments, buffer ) )
我得到这个错误:
无法将“[String]”类型的值转换为预期的参数类型
“不安全的指针!”
对于CommandLine.arguments,我尝试将其用作
argv
。有人知道getopt
的第二个参数的正确语法吗?提前谢谢 CommandLine.arguments
为您提供了一个友好的Swift[String]
传递的参数–但是您希望将参数直接发送回C。因此,您可以简单地使用它,它将为您提供传递给程序的argv
的实际原始值
let option = Int( getopt( CommandLine.argc, CommandLine.unsafeArgv, buffer ) )
@哈米什已经回答了这个问题,并解释了如何在Swift中将
CommandLine.gv
传递到getopt()
(以及为什么)
下面是一个完整的自包含示例,演示了典型的getopt
循环可以在Swift 3中实现:
var aFlag = false
var bFlag = false
var cValue: String?
while case let option = getopt(CommandLine.argc, CommandLine.unsafeArgv, "abc:"), option != -1 {
switch UnicodeScalar(CUnsignedChar(option)) {
case "a":
aFlag = true
case "b":
bFlag = true
case "c":
cValue = String(cString: optarg)
default:
fatalError("Unknown option")
}
}
print(aFlag, bFlag, cValue ?? "?")
备注:
- 您可以将Swift字符串(此处:
)直接传递给C 函数需要一个(常量)C字符串,编译器将自动 生成临时UTF-8表示“abc:
返回getopt()
(如果参数列表已用尽)或转换为-1
的int
无符号字符。因此,使用 将返回值转换为
(在Swift中为CUnsignedChar
)UInt8
与模式匹配一起使用(滥用?) 实现典型C模式的布尔条件while
迅速地while ((option = getopt(argc, argv, "abc:")) != -1) { ... }
'UnsafePointer?>!'代码>部分?当我回到控制台前时,我会再次检查,但我相信是的。@Alexander这是一个标记格式错误;我修好了
while ((option = getopt(argc, argv, "abc:")) != -1) { ... }