没有"Expression pattern of type 'Range<Double>' cannot match values of type 'Int'"就无法使函数工作



这是我尝试过的,无法弄清楚错误来自哪里。是不是少了点什么?语法错误?我尝试在函数中使用 if-else 做类似的事情,但也出现错误。

var steps = 0
func incrementSteps() -> Int {
steps += 1
print(steps)
return steps
}
incrementSteps()
let goal = 10000
func progressUpdate() -> Int {
let updated = progressUpdate()/goal
switch updated {
case (0.0..<0.1):
print("Great start")
case (0.11..<0.5):
print("Almost halfway")
case (0.51..<0.9):
print("Almost complete")
default:
print("Beat goal")
}
}
progressUpdate()

您需要将updated指定为Double。并在返回时将其投回Int(如果您需要Int满足您的要求(。

注意:此外,您需要修改在定义progressUpdate调用progressUpdate函数,这会导致递归。如果要这样做,可能需要为break循环提供条件。

func progressUpdate() -> Int {
let updated = Double(steps/goal)
switch updated {
case (0.0..<0.1):
print("Great start")
case (0.11..<0.5):
print("Almost halfway")
case (0.51..<0.9):
print("Almost complete")
default:
print("Beat goal")
}
return Int(updated)
}

相关内容

最新更新