在 Swift 中初始化类实例和访问变量

在 Swift 中初始化类实例和访问变量

问题描述:

我刚刚创建了一个类并给了它一些变量.不幸的是,我无法在我的 iOS-Projects 中访问这些变量.但是,相同的语法在操场上也有效...

I just created a class and gave it some vars. Unfortunately I can't access these variables in my iOS-Projects. However, the same syntax works in playground...

class ViewController: UIViewController 
{
    class Dog 
    {
        var age = 0
        var hungry = TRUE
    }
    var rex = Dog()
    rex.age = 2   //ERROR: EXPECTED DECLARATION
}

类声明的语法是:

class <class name>: <superclass>, <adopted protocols> {
  <declarations>
}

您对 ViewController 的声明包括 rex.age = 2,它本身不是一个声明,而是一个声明 - 特别是带有中缀运算符的二元表达式.

Your declaration of ViewController includes rex.age = 2 which itself is not a declaration, it is a statement - specifically a binary expression with an infix operator.