我是swift编程的新手。我在windows或在线编译器中编译我的程序。我在swift中读了一个整数。我成功地从控制台读取了整数。但是我不能在while循环中使用这个整数变量。如何在while循环中使用从控制台读取整型变量?我的尝试是:
import Foundation
print("Enter a number:")
let inputNumber = Int(readLine()!)
if let inputNumber = inputNumber {
print(inputNumber)
}
if inputNumber == 3 {
print("number = 3") }
else { print("number != 3") }
var sayi = inputNumber
if sayi == 3 {
print("sayi = 3") }
else { print("sayi != 3") }
while sayi > 0 {
print("*", terminator:"")
sayi = sayi - 1 }编译错误包括:
main.swift:21:12:错误:二元运算符'>‘不能应用于类型为'Int?’的操作数和“Int”
当sayi >0{^~
main.swift:21:12:注意:'>‘的重载存在以下部分匹配的参数列表:(Self,Self),(Self,Other)
当sayi >0{^
main.swift:23:16:错误:可选类型'Int?‘的值没有展开;您的意思是要使用'!‘吗?还是“?”?sayi = sayi -1
发布于 2020-10-15 20:48:05
问题是inputNumber和sayi是可选值,编译器认为Int和Int?是无法比较的不同类型
我将使用以下逻辑来读取和转换用户输入
let inputNumber: Int
//The below if clause will be successful only if both deadline() and Int() returns non-nil values
if let input = readLine(), let value = Int(input) {
inputNumber = value
} else {
print("Bad input")
inputNumber = 0
}然后剩下的代码就可以工作了(这里我稍微简化了一下)
var sayi = inputNumber
sayi == 3 ? print("sayi = 3") : print("sayi != 3")
while sayi > 0 {
print("*", terminator:"")
sayi -= 1
}https://stackoverflow.com/questions/64371570
复制相似问题