Swift 为什么我会得到可选类型';字符串';readLine()收集的用户输入出错?如何强制用户只输入所需的数据类型?
我正在尝试编写一个递增函数,当列表中的数字按递增顺序排列时,该函数将返回true。首先,我编写了var input=readLine()来获取用户输入,并将isIncreasing直接应用于输入。我收到错误:可选类型“字符串”的值未展开;你想用“!”吗还是“?”?为了消除这个错误,我决定只在程序确定输入是整数数组的情况下应用ISincreating函数。然而,即使在我编写了将用户输入转换为整数数组的行之后,我仍然会得到相同的错误Swift 为什么我会得到可选类型';字符串';readLine()收集的用户输入出错?如何强制用户只输入所需的数据类型?,swift,swift3,Swift,Swift3,我正在尝试编写一个递增函数,当列表中的数字按递增顺序排列时,该函数将返回true。首先,我编写了var input=readLine()来获取用户输入,并将isIncreasing直接应用于输入。我收到错误:可选类型“字符串”的值未展开;你想用“!”吗还是“?”?为了消除这个错误,我决定只在程序确定输入是整数数组的情况下应用ISincreating函数。然而,即使在我编写了将用户输入转换为整数数组的行之后,我仍然会得到相同的错误 var result: Bool = true func isI
var result: Bool = true
func isIncreasing(_ num: [Int]) -> Bool{
for i in num{
if(num[i] < num[i + 1]){
result = true
}
else{
result = false
}
}
return result
}
print("Type in a list of integers")
var input = readLine()
if (type(of: input) == type(of: "val")){ //changing types into [Int] to get rid of the optional type 'String' error
var arg = [Int]()
for element in input.characters
//I am still gtting the error: swift:20:20: error: value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?
{
arg.append(Int(String(element))!)
}
isIncreasing(arg)
}
//var arg: [Int] = Array(input).map { String($0).toInt()! }
var结果:Bool=true
func正在增加(num:[Int])->Bool{
因为我在num{
if(num[i]
if let-input=readLine(){
将字符串上的数字转换为Intlet-arg=input.compactMap{$0.wholeNumberValue}
Btw为什么要使用Swift 3?如果确实需要Swift 3 codelet-arg=input.compactMap{Int(String($0)),只需从应用商店将Xcode更新为最新版本即可
非常感谢。我之所以使用swift 3,是因为我正在Windows上编写swift,而我目前还无法访问mac电脑。