我之前已经意识到这一点,但是这里的答案(在块之外声明变量)似乎不起作用。 link description
var filter: String
func Usage() {
print("Usage: <filter> <input> [output]")
print("System filter paths do not need to be specified.")
return
}
let arguments = ["qwe", "value", "qwe", "asd"]
print(arguments.count)
switch arguments.count {
case 1:
Usage()
case 2:
Usage()
case 3:
filter = arguments[1]
default:
filter = arguments[1]
print (filter)
}
print (filter)
我得到&#34;价值&#34;在Xcode的第一次打印的游乐场,但第二次给出了#34; \ n&#34;或&#34;值未初始化&#34;。 我做错了什么?
答案 0 :(得分:3)
您的代码首先不会编译,您会收到错误error: variable 'filter' used before being initialized
所以声明过滤器如下:
var filter = String()
或var filter = ""
其次,因为你没有添加所有代码,我尝试了以下内容:
var filter = String()
let x = 0
switch x {
case 1:
print("1")
default:
filter = "value"
print(filter)
}
print(filter)
打印出来:
value
value
如果您需要进一步的帮助,请通过更多信息更新您的问题。
<强>更新强>
刚试过更新的代码:
var filter = String()
让参数= [“qwe”,“value”,“qwe”,“asd”]
打印(arguments.count)
switch arguments.count {
情况1:
打破
案例2:
打破
案例3:
filter = arguments [1]
default:
filter = arguments[1]
print (filter)
}
print (filter)
这打印出来:
4
value
value
这正是应该打印出来的。记住filter
的初始化。
更新2:
这是你想要做的,你的另一个结果总是返回4,因为这是arguments
的计数。请尝试使用以下代码。
var filter = String()
func Usage() {
print("Usage: <filter> <input> [output]")
print("System filter paths do not need to be specified.")
return
}
let arguments = ["qwe", "value", "qwe", "asd"]
print(arguments.count)
for i in 0..<arguments.count {
switch i {
case 0:
Usage()
case 1:
Usage()
case 2:
Usage()
case 3:
filter = arguments[1]
default:
filter = arguments[1]
print (filter)
}
}
print (filter)
打印出来:
4
Usage: <filter> <input> [output]
System filter paths do not need to be specified.
Usage: <filter> <input> [output]
System filter paths do not need to be specified.
Usage: <filter> <input> [output]
System filter paths do not need to be specified.
value
答案 1 :(得分:1)
您的代码似乎是命令行界面的入口点。
这是一种替代方法,无需声明全局变量且没有switch
。
Usage
,否则CLI名称(索引0)后的前两个参数将分配给两个变量。
let arguments = ["qwe", "value", "qwe", "asd"]
print(arguments.count)
if arguments.count < 3 {
Usage()
exit(EXIT_FAILURE)
}
let filter = arguments[1]
let secondArgument = arguments[2]
print (filter, secondArgument)
然后你可以在switch
filter
switch filter {
case "value": doThis(with: secondArgument)
case "someOtherFilter": doThat(with: secondArgument)
default: doNothing()
}