简体   繁体   English

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

[英]Initialize class-instance and access variables in Swift

I just created a class and gave it some vars. 我刚刚创建了一个类,并给了它一些变量。 Unfortunately I can't access these variables in my iOS-Projects . 不幸的是,我无法在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
}

The last two lines need to be inside a function. 最后两行需要在函数内部。 You can have only declarations in class scope, not expressions to be executed. 您只能在类范围内具有声明,而不能执行要执行的表达式。

The syntax for a class declaration is: 类声明的语法是:

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

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. 您的ViewController声明包括rex.age = 2 ,它本身不是声明 ,它是一个声明 - 特别是带有中缀运算符的二进制表达式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM