【问题标题】:How can I read system input in Swift easily如何轻松读取 Swift 中的系统输入
【发布时间】:2020-12-25 12:41:27
【问题描述】:

我是 Swift 的初学者,我很难处理 Swift String。
我认为它与其他语言有很多不同。

那么,谁能告诉我为什么这个说法不正确?

我想读取一行并将每个整数插入变量n, l

在 C 中,像这样 -> scanf("%d %d", &n, &l);

var n, l : Int?
var read : String = readLine()!
n = Int(read[read.startIndex])
l = read[read.index(read.startIndex, offsetBy : 2)]

【问题讨论】:

标签: swift string


【解决方案1】:

在 Swift 中处理 cli 工具输入的最佳方式可能是使用官方的 ArgumentParser 库。

但是一个超级幼稚的实现会涉及到这样的事情:

  • 读取输入
  • 用空格分割
  • 尝试解析成Ints

下面的例子当然不能用于学习以外的任何事情......:

print("Please input 2 numbers separated by space:")

let read = readLine()

if let inputs = read?.split(separator: " ") // Split using space
        .map(String.init)                   // Convert substring to string
        .compactMap(Int.init),              // Try to convert to Ints (get rid of nils)
        inputs.count > 1 {                  // Ensure that we got at least 2 elements
            let (n, l) = (inputs[0], inputs[1])
            print(n, l)
} else {
    // Handle the case
}

【讨论】:

  • 可以合并第二张地图和compactMap到compactMap { Int($0) }
  • @JoakimDanielson 当然。你说得对,我先写了 cmets,然后写了代码,但我猜代码越少越好:P 谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多