gpt4 book ai didi

swift - 允许程序从 Swift 中的标准输入或参数读取

转载 作者:行者123 更新时间:2023-12-05 02:58:24 26 4
gpt4 key购买 nike

我正在尝试编写一个 Swift 程序

  • 接受来自标准输入的单个参数或管道数据,并打印出来
  • 如果两者都缺失,则打印一条用法消息。

假设代码包含在main.swift中,我们有四种情况:

  1. swift main.swift 应该输出“请提供一些输入”
  2. swift main.swift argument 应该输出“argument”
  3. 回显 | swift main.swift 应该输出“请提供一些输入”
  4. 回显参数 | 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)

但是,回显参数 | 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() 导致执行暂停,等待输入。如果您在没有输入的情况下按回车键,则会返回正确的消息,但我想避免手动输入空白行的必要性。

当标准输入为空且没有参数时,如何从标准输入读取启用读取,同时不导致暂停?

最佳答案

我认为问题是 readLine() 将只是等待某种输入,即使它只是使用 ctrl-d 发送结束线到它。对于您的使用,是否可以添加一个参数来告诉程序它应该等待输入?否则,它可以假设它不应该等待任何事情吗?

例如:

import Foundation

func readInput () -> String? {
var input:String?

while let line = readLine() {
if input == nil {
if line.isEmpty { break }
input = line
} else {
input! += "\n" + line
}
}

return input
}

var input: String? = nil

if CommandLine.arguments.count > 1 {
input = CommandLine.arguments[1]

if (input == "-i") {
input = readInput()
}
}

guard let input = input else {
print("Please provide some input")
exit(0)
}

print("input: \(input)")

然后你最终得到这样的用法和输出:

Screenshot of program output.

关于swift - 允许程序从 Swift 中的标准输入或参数读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59060151/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com