gpt4 book ai didi

swift - 为什么每次我尝试让用户在 Swift 中输入整数时,Xcode 都会让我在变量后面加上 "!"

转载 作者:行者123 更新时间:2023-11-30 10:50:43 25 4
gpt4 key购买 nike

我正在编写一个代码,我需要获取 2 个用户输入的整数并输出较小的一个。我是 swift 新手,每次尝试让用户输入整数时,都会收到此错误“可选类型‘字符串的值?’”必须解包为“String”类型的值”。我不明白为什么我总是需要加一个“!”在 readLine() 之后,但这就是它让我做的事情。

print("Enter the first integer")
let int1 = Int(readLine()!)
print("Enter the second integer")
let int2 = Int(readLine()!)
let small_int = min(int1!, int2!)
print("The smaller integer is", small_int)

最佳答案

正如您可以在 docs 中读到的那样:

The string of characters read from standard input. If EOF has already been reached when readLine() is called, the result is nil.

...所以,简单地说,readLine(strippingNewline:) 总是不必返回值,它也可以返回 nil (无值),所以返回type is String? 这是可选类型,表示您的常量是 Stringnil

如果您需要获取非可选值,您可以强制解包可选值或检查值是否存在,如果存在,则使用可选绑定(bind)分配一些非可选常量/变量。您可以对 Int 初始化程序执行相同的操作,它也可以返回 nil,因为并非每个 String 都一定是整数

print("Enter the first integer")
let input1 = readLine()
print("Enter the second integer")
let input2 = readLine()

if let string1 = input1, let int1 = Int(string1), let string2 = input2, let int2 = Int(string2) {
let small_int = min(int1, int2)
print("The smaller integer is", small_int)
} else {
print("Invalid input")
}

或者,您可以使用默认值,因此如果值为nil,您的常量将被分配给定的默认值

print("Enter the first integer")
let int1 = Int(readLine() ?? "") ?? 0
print("Enter the second integer")
let int2 = Int(readLine() ?? "") ?? 0
let small_int = min(int1, int2)
print("The smaller integer is", small_int)

关于swift - 为什么每次我尝试让用户在 Swift 中输入整数时,Xcode 都会让我在变量后面加上 "!",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54609587/

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