Swift 可选 - 条件中的变量绑定需要初始化程序

Swift Optionals - Variable binding in a condition requires an initializer

我是 Swift 的新手,正在尝试了解可选概念。我在 Playground 中有一小段代码给我 "Variable binding in a condition requires an initializer" 错误。有人可以解释为什么以及如何解决它吗?

我只想打印 "Yes" 或 "No" 取决于 "score1" 是否有值。这是代码:

import Cocoa

class Person {
    var score1: Int? = 9

    func sum() {
        if let score1 {
            print("yes")
        } else {
            print("No")
        }
    }//end sum
 }// end person

 var objperson = person()
 objperson.sum()

问题是 if let 假定您想要创建一个具有某些值的常量 score1。如果你只是想检查它是否包含一个值,如 not nil 你应该像下面那样做:

if score1! != nil {
     // println("yes")

因此您的完整代码如下所示:

class Person {
    var score1: Int? = 9

    func sum() {
        if score1 != nil {
            println("yes")
        }
        else {
            println("no")
        }
    }
}

var objperson = Person()
objperson.sum()

写作

if let score1 {

没有意义。如果要查看score是否有值,使用

if score1 != nil {

if let score = score1 {

最后一个案例将一个新的非可选常量 score 绑定到 score1。这使您可以在 if 语句中使用 score

if let 语句接受一个可选变量。如果为 nil,则不执行 else 块或不执行任何操作。如果它有一个值,该值将作为非可选类型分配给另一个变量。

所以,如果有none,下面的代码将输出score1或"No"的值:

if let score1Unwrapped = score1
{
    print(score1Unwrapped)

}

else
{
    print("No")
}

相同的较短版本是:

print(score1 ?? "No")

在你的情况下,你实际上并没有使用存储在可选变量中的值,你还可以检查该值是否为 nil:

if score1 != nil {
...
}