【发布时间】:2019-11-26 22:14:29
【问题描述】:
我正在尝试编写一个 Swift 程序
- 接受来自标准输入的单个参数或管道数据,并打印出来
- 如果两者都缺失,则打印使用消息。
假设代码包含在main.swift中,我们有四种情况:
-
swift main.swift应该输出“请提供一些输入” -
swift main.swift argument应该输出“argument” -
echo | swift main.swift应该输出“请提供一些输入” -
echo argument | swift main.swift应该输出“argument”
对于复合 echo argument1 | swift main.swift argument2,argument2 优先。
满足1-3很简单:
import Foundation
var input: String? = nil
if CommandLine.arguments.count > 1 {
input = CommandLine.arguments[1]
}
guard let input = input else {
print("Please provide some input")
exit(0)
}
print(input)
但是,echo argument | swift main.swift 显然会打印使用消息,因为没有参数。添加一些代码,
import Foundation
var input: String? = nil
if CommandLine.arguments.count > 1 {
input = CommandLine.arguments[1]
} else {
while let line = readLine() {
if input == nil {
if line.isEmpty { break }
input = line
} else {
input! += "\n" + line
}
}
}
guard let input = input else {
print("Please provide some input")
exit(0)
}
print(input)
现在案例 2-4 可以正常工作,但案例 1 有问题。 readLine() 导致执行暂停,等待输入。如果您在没有输入的情况下按回车,则会返回正确的消息,但我想避免手动输入空行的必要性。
如何从标准输入读取启用读取,同时在标准输入为空白且没有参数时不会导致暂停?
【问题讨论】:
标签: swift command-line-arguments stdin