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() 的相关文章

  • Swift:如何减少 didupdatelocations 调用

    我想出了一些代码来打印我所在位置的地址和邮政编码 这是在 didupdatelocation 函数中完成的 我遇到的唯一问题是 didupdatelocation 函数每秒都会更新该地址 因为这电池效率非常低 所以我一直在寻找使用间隔的方法
  • 在 SwiftUI 中使用分段式选取器在两个页面之间滑动

    我有一个Picker with pickerStyle SegmentedPickerStyle 使其成为分段控件 我想让页面在之间平滑滑动 而不是使用条件语句替换视图 这是我迄今为止所做的 gif 这是到目前为止的代码 由if 而不是在不
  • 为什么我不能在 Realm 属性上使用 private

    我正在尝试在 RealmSwift 中存储一个枚举案例 但 Realm 不支持枚举 本文 https medium com it works locally persisting swift enumerations with realm
  • 如何将字符串日期转换为 NSDate?

    我想转换字符串 2014 07 15 06 55 14 198000 00 00 to an NSDate在斯威夫特 尝试这个 let dateFormatter NSDateFormatter dateFormatter dateForm
  • 所需框架与静态库

    构建现代框架 https developer apple com videos play wwdc2014 416 says 每个应用程序都有自己的自定义框架副本 https stackoverflow com a 15262463 242
  • NVActivityIndi​​catorView 仅适用于特定视图

    我正在使用这个库https github com ninjaprox NVActivityIndi catorView https github com ninjaprox NVActivityIndicatorView用于显示加载指示器
  • 在现有 iOS 应用程序中集成 React-native(0.40.0) 后找不到 Yoga/Yoga.h 头文件

    在我的 Swift iOS 应用程序中集成 React Native 后 我无法构建 yoga Yoga h file cannot be found 我已经浏览了文档 查看了react native github页面 检查了类似问题的SO
  • Swift 闭包作为 AnyObject

    我尝试使用这个方法 class addMethod 在 Obj c 中使用如下 class addMethod self class selector eventHandler imp implementationWithBlock han
  • 如何防止 RealmSwift 列表中出现重复项?

    如何防止向列表中添加重复项RealmSwift 我有我的User作为领域对象 但真正的数据源是服务器 只是使用领域在本地缓存用户 当我从服务器获取当前用户数据时 我想确保存储在领域中的用户拥有来自服务器的所有播放列表 以及它们的曲目列表等
  • 在 iOS 11 中创建 Gif 图像颜色贴图

    最近 我在创建 Gif 时遇到了一个问题 如果它太大 颜色就会丢失 然而 感谢 SO 的帮助 有人能够帮助我找到解决方法并创建我自己的颜色图 上一个问题在这里 保存动画 Gif 时 iOS 颜色不正确 https stackoverflow
  • iOS 11 安全区域布局指南向后兼容性

    启用安全区域布局指南是否与 iOS 11 以下版本兼容 我设法使用新的安全区域布局指南并保持与 iOS 9 和 iOS 10 的向后兼容性 编辑 正如 NickEntin 的评论所指出的 此实现将假定存在状态栏 但在 iPhone X 的横
  • 在 Swift 中自动移动 UISlider

    我想在按下按钮时将 UISlider 从 minValue 循环移动到 maxValue 并在再次按下按钮时将其停止在当前位置 我想使用 Swift 我遇到的主要问题是函数 slider setValue 太快了 我希望动画更慢 IBAct
  • 如何使用 Swift 获取 YouTube 频道的所有播放列表?

    我的问题不是关于从一般频道检索视频 我只想获取该频道创建的所有 播放列表 并检索每个播放列表的缩略图 标题和视频数量 这是一个 YouTube 频道示例 正如您所看到的 有很多已创建的播放列表 截至目前 我只能获取某个频道最新上传的视频 在
  • NSPredicate 的 onFormat 字符串

    我想用 id 键对数据进行排序 我如何理解格式字符串的用途NSPredicate格式 我有一个100号的帖子 我的代码 let objectIDs posts map 0 id let predicate NSPredicate forma
  • Obj-C / Swift 项目中的致命陷阱异常

    我开始将 Swift 代码集成到我的 Obj C 项目中 一切都进展顺利 但今天 当我更新到 Xcode 6 1 时 事情变得很糟糕 我从之前运行良好的 Swift 代码中收到了许多 陷阱 异常 第一次崩溃位于我的 UIFont 扩展中 这
  • 在 swift 中获取 NSImage 的 PNG 表示

    嘿 我在获取 NSImage 对象的 PNG 表示时遇到了一些问题 这就是我正在做的 var imgData NSData coverImgView image TIFFRepresentation var bitmap NSBitmapI
  • 测试文本字段中的 double 是否有值

    尝试检查从文本字段获得的双变量是否有值 让值 双倍 Double valueTextfield text if value isEmpty X if 值 nil X 如果 值 0 X 我该怎么做呢 您可以使用 Double 的 init 方
  • NSURLConnection 的 URL 文件大小 - Swift

    我想在下载之前从 url 获取文件大小 这是 obj c 代码 NSURL URL NSURL URLWithString ExampleURL NSMutableURLRequest request NSMutableURLRequest
  • 斯威夫特/iOS。从导航堆栈中删除一些视图控制器

    这是我想做的 但我不确定这是否是正确的方法 所以请给我建议如何去做 我有初始 VC 和导航 VC 我从中推送第一个 VC 从中推送第二个 VC 接下来我介绍 来自第二个 VC 的 NavigationController 第三个 VC 现在
  • Swift 中的字典是否应该转换为类或结构?

    我正在开发一个本机 iOS 应用程序 该应用程序从我们也可以控制的 Web 服务接收 JSON 格式的数据 该计划是在大约 18 个月内更换后端数据库 以支持不同的平台 考虑到这一点 我们希望确保 iOS 应用程序能够相对容易地适应新的数据

随机推荐