gpt4 book ai didi

swift - 如何将 readLine() 的 Swift 3 输出转换为整数?

转载 作者:搜寻专家 更新时间:2023-10-31 08:25:33 28 4
gpt4 key购买 nike

在阅读全部内容之前,请不要标记为重复。这是 Swift 3 特有的。

我有一些函数有参数,例如 Ints、Floats 等。我想获取 readLine() 的输出并让 Swift 接受 readLine() 的输出作为这些类型,但不幸的是 readLine() 输出一个字符串?当我尝试转换时,它告诉我它没有打开。我需要帮助。我正在使用 Ubuntu 16.04。

例如,如果我有 area(width: 15, height: 15),我如何将 15 和 15 替换为两个包含 readLine() 或任何等效于 readLine() 的常量以接受来自终端用户的输入?

另请注意,我正在编写的程序专门用于数学运算,因为大多数人似乎对字符串很满意,这实际上是一个基于 CLI 的计算器。

编辑 1(笑) 好的,这是对上述内容的更准确的解释。以下代码将打印梯形的面积:

import Foundation

func areaTrapezoid(height: Float, baseOne: Float, baseTwo: Float) {
let inside = baseOne + baseTwo
let outside = 0.5 * height
let result = outside * inside
print("Area of Trapezoid is \(result)")
}

areaTrapezoid(height: 10, baseOne: 2, baseTwo: 3)

因此,梯形的高度为 10 个单位,两个底边的长度分别为 2 和 3。但是,我想做类似的事情:

import Foundation

func areaTrapezoid(height: Float, baseOne: Float, baseTwo: Float) {
let inside = baseOne + baseTwo
let outside = 0.5 * height
let result = outside * inside
print("Area of Trapezoid is \(result)")
}

let h = readLine()
areaTrapezoid(height: h, baseOne: 2, baseTwo: 3)

除此之外,已经很明显,readLine() 将输出一个可选字符串,而不是 Float。如果您愿意,我希望用户能够以某种交互方式通过 CLI 输入数字。我只是在学习 Swift,但在学习该语言时,我在 C++ 中做了类似的事情。感谢您提供的任何帮助。

最佳答案

readLine() 返回可选字符串。

要解包字符串,可以使用 if let,要将字符串转换为整数,请使用 Int()

例子:

import Foundation
if let typed = readLine() {
if let num = Int(typed) {
print(num)
}
}

假设您提示用户两次:

let prompt1 = readLine()
let prompt2 = readLine()

然后:

if let response1 = prompt1, 
response2 = prompt2,
num1 = Int(response1),
num2 = Int(response2) {
print("The sum of \(num1) and \(num2) is \(num1 + num2)")
}

关于swift - 如何将 readLine() 的 Swift 3 输出转换为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38167580/

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