Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize class-instance and access variables in Swift

Tags:

swift

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
}
like image 339
DanielAsking Avatar asked Mar 04 '26 09:03

DanielAsking


1 Answers

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.

like image 158
GoZoner Avatar answered Mar 05 '26 22:03

GoZoner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!