Initialize class and instance variables in Swift

I just created a class and gave it some vars. Unfortunately, I cannot access these variables in mine iOS-Projects. However, the same syntax works on the playground ...

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

Class declaration syntax:

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

Your ad ViewControllercontains rex.age = 2, which in itself is not an ad, it is an operator - in particular a binary expression with an infix operator.

+5
source

The last two lines should be inside the function. You can only have declarations in the class, not expressions that must be executed.

+5
source

All Articles