在 Swift 中使用条件时遇到问题



我陷入了以下问题集。有什么想法吗?

var hasFuel == "true"
if hasFuel == "true" {
print("Let's go for a drive")
} else if hasFuel != "true" {
print("We're not going anywhere!")
}

这是赋值运算符与相等运算符的错误。

代码无法编译

"=="不是前缀一元运算符

您可能希望分配

var hasFuel = "true"

更好

var hasFuel = true

这避免了第二个if

if hasFuel == true {
print("Let's go for a drive")
} else {
print("We're not going anywhere!")
}

或更短

if hasFuel {
print("Let's go for a drive")
} else {
print("We're not going anywhere!")
}

最新更新