readline_Swift readLine(),Swift print()

2023-05-16

readline

In this tutorial, we’ll be discussing how to read the standard input in Swift from the user and the different ways to print the output onto the screen. Swift print() is the standard function to display an output onto the screen.

在本教程中,我们将讨论如何从用户中读取Swift中的标准输入以及将输出打印到屏幕上的不同方法。 Swift print()是在屏幕上显示输出的标准函数。

Let’s get started by creating a new command line application project in XCode.

让我们开始使用XCode创建一个新的命令行应用程序项目。

快速输入 (Swift Input)

In Swift, the standard input is not possible in Playgrounds. Neither in iOS Application for obvious reasons. Command Line Application is the possible way to read inputs from the user.

在Swift中,标准输入在Playgrounds中是不可能的。 出于明显的原因,iOS应用程序中都没有。 命令行应用程序是从用户读取输入的可能方法。

readLine() is used to read the input from the user. It has two forms:

readLine()用于从用户读取输入。 它有两种形式:

  • readLine() : The default way.

    readLine() :默认方式。
  • readLine(strippingNewLine: Bool) : This is default set to true. Swift always assumes that the newline is not a part of the input

    readLine(strippingNewLine: Bool) :默认设置为true。 Swift始终假定换行符不是输入的一部分

readLine() function always returns an Optional String by default.

默认情况下, readLine() 函数始终返回可选 字符串 。

Add the following line in your main.swift file.

main.swift文件中添加以下行。

let str = readLine() //assume you enter your Name
print(str) //prints Optional(name)

To unwrap the optional we can use the following code:

要打开可选的包装,我们可以使用以下代码:

if let str = readLine(){
print(str)
}

读取Int或Float (Reading an Int or a Float)

To read the input as an Int or a Float, we need to convert the returned String from the input into one of these.

要将输入读取为Int或Float,我们需要将输入返回的String转换为其中之一。

if let input = readLine()
{
    if let int = Int(input)
    {
        print("Entered input is \(int) of the type:\(type(of: int))")
    }
    else{
        print("Entered input is \(input) of the type:\(type(of: input))")
    }
}

For Float, replace Int initialiser with the Float.

对于Float,将Int 初始化程序替换为Float。

读取多个输入 (Reading Multiple Inputs)

The following code reads multiple inputs and also checks if any of the input is repeated.

以下代码读取多个输入,还检查是否重复了任何输入。

while let input = readLine() {
    guard input != "quit" else {
        break
    }
    
    if !inputArray.contains(input) {
        inputArray.append(input)
        print("You entered: \(input)")
    } else {
        print("Negative. \"\(input)\" already exits")
    }
    
    print()
    print("Enter a word:")
}

The guard let statement is used to exit the loop when a particular string is entered
print() as usual prints the output onto the screen. The current input is checked in the array, if it doesn’t exist it gets added.

输入特定字符串时,将使用guard let语句退出循环
与往常一样, print()将输出打印到屏幕上。 在数组中检查当前输入,如果不存在,则将其添加。

A sample result of the above code when run on the command line in Xcode is given below.

下面给出了在Xcode的命令行上运行时上述代码的示例结果。

读取由空格分隔的输入 (Reading Input Separated by Spaces)

The following code reads the inputs in the form of an array separated by spaces.

以下代码以空格分隔的数组形式读取输入。

let array = readLine()?
    .split {$0 == " "}
    .map (String.init)

if let stringArray = array {
    print(stringArray)
}

split function acts as a delimiter for spaces. It divides the input by spaces and maps each of them as a String. Finally they’re joined in the form of an array.

split函数充当空格的定界符。 它将输入除以空格并将每个映射为String。 最后,它们以数组的形式加入。

读取2D阵列 (Reading a 2D Array)

The following code reads a 2D Array

以下代码读取2D数组

var arr = [[Int]]()
for _ in 0...4 {
    var aux = [Int]()

    readLine()?.split(separator: " ").map({
        if let x = Int($0) {
        aux.append(x)
        }
        else{
            print("Invalid")
        }
    })
    arr.append(aux)
}

print(arr)

In the above code we can create 4 sub arrays inside an array.
If at any stage we press enter without entering anything in the row, it’ll be treated as a empty subarray.

在上面的代码中,我们可以在一个数组内创建4个子数组。
如果在任何阶段我们按Enter键但未在行中输入任何内容,则它将被视为空子数组。

迅捷print() (Swift print())

We’ve often used print() statement in our standard outputs.

我们经常在标准输出中使用print()语句。

The print function actually looks like this:

打印功能实际上如下所示:

print(_:separator:terminator:)

print(_:separator:terminator:)

print() statement is followed by a default new line terminator by default

默认情况下, print()语句后接默认的新行终止符

print(1...5)  Prints "1...5"

print(1.0, 2.0, 3.0, 4.0, 5.0) //1.0 2.0 3.0 4.0 5.0

print("1","2","3", separator: ":") //1:2:3

for n in 1...5 {
    print(n, terminator: "|")
}
//prints : 1|2|3|4|5|
  • terminator adds at the end of each print statement.

    终止符在每个打印语句的末尾添加。
  • separator adds between the output values.

    分隔符在输出值之间相加。

Concatenating string with values
We use \(value_goes_here) to add values inside a string.

将字符串与值连接
我们使用\(value_goes_here)在字符串中添加值。

var value = 10
print("Value is \(value)") // Value is 10

This brings an end to this tutorial on Swift Standard Input and Output.

这样就结束了有关Swift标准输入和输出的本教程。

翻译自: https://www.journaldev.com/19612/swift-readline-swift-print

readline

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

readline_Swift readLine(),Swift print() 的相关文章

随机推荐