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. Let's get started by creating a new command line application project in XCode.
快速入口
在Swift中,标准输入在Playgrounds中是不可能的,也不是在iOS应用程序中,出于显而易见的原因,命令行应用程序是读取用户输入的可能方式。
readLine()
: 默认方式.readLine(strippingNewLine: Bool)
: 这是默认设置为 true。
readLine()
函数总会按默认值返回 Optional String 将下列行添加到您的 main.swift
文件中。
1let str = readLine() //assume you enter your Name
2print(str) //prints Optional(name)
要卸载可选,我们可以使用以下代码:
1if let str = readLine(){
2print(str)
3}
阅读 Int 或 Float
要将输入读成 Int 或 Float,我们需要将返回的 String 从输入转换为其中一个。
1if let input = readLine()
2{
3 if let int = Int(input)
4 {
5 print("Entered input is \(int) of the type:\(type(of: int))")
6 }
7 else{
8 print("Entered input is \(input) of the type:\(type(of: input))")
9 }
10}
在 Float 中,用 Float 替换 Int initialiser。
阅读多重输入
以下代码读取多个输入,并检查任何输入是否重复。
1while let input = readLine() {
2 guard input != "quit" else {
3 break
4 }
5
6 if !inputArray.contains(input) {
7 inputArray.append(input)
8 print("You entered: \(input)")
9 } else {
10 print("Negative. \"\(input)\" already exits")
11 }
12
13 print()
14 print("Enter a word:")
15}
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. A sample result of the above code when run on the command line in Xcode is given below.
通过空间分开的阅读输入
以下代码读取输入以间隔隔的数组的形式。
1let array = readLine()?
2 .split {$0 == " "}
3 .map (String.init)
4
5if let stringArray = array {
6 print(stringArray)
7}
split 函数作为空间的界限器,它将输入分为空间,并将每个空间作为一个字符串绘制。
阅读2D Array
以下代码读取2D Array
1var arr = [[Int]]()
2for _ in 0...4 {
3 var aux = [Int]()
4
5 readLine()?.split(separator: " ").map({
6 if let x = Int($0) {
7 aux.append(x)
8 }
9 else{
10 print("Invalid")
11 }
12 })
13 arr.append(aux)
14}
15
16print(arr)
在上面的代码中,我们可以创建一个数组内的4个子数组. 如果在任何阶段我们按入而不输入任何东西,它将被视为一个空的子数组。
快速打印( )
在我们的标准输出中,我们经常使用print()
语句. 打印函数实际上看起来是这样的:print(_:separator:terminator:)``print()
语句是由默认的新行终结器随之而来。
1print(1...5) //// Prints "1...5"
2
3print(1.0, 2.0, 3.0, 4.0, 5.0) //1.0 2.0 3.0 4.0 5.0
4
5print("1","2","3", separator: ":") //1:2:3
6
7for n in 1...5 {
8 print(n, terminator: "|")
9}
10//prints : 1|2|3|4|5|
- 终结器**在每个打印语句的末尾添加
- 分离器**在输出值之间添加
** 链接字符串与值** 我们使用 (value_goes_here)
添加字符串中的值。
1var value = 10
2print("Value is \(value)") // Value is 10
这就结束了这个关于Swift标准输入和输出的教程。