Not allowed to initialize instance variables?

I have an extremely simple class that I just started writing, and it's already gone wrong. The following gives me a compiler error:

init (foo: Int, bar: Int, bat: Float) { = foo = bar
        self.bat = bat
        self.extra = 12345

There is no superclass, so I'm not allowed to call super.init().

The error I get is:

'self' used in property access 'foo' before all stored properties are initialized

Well OK, how am I supposed to initialize stored properties before I initialize stored properties?

Foo and bat both have getters and setters, but bar and extra do not.
How to understand what's going on?
I've never gotten thwarted with such simple code in C, C++, Python or anything else really.

You are seeing the definite-initialization rule in action, which saves you from using variables that are not initialized yet. :slight_smile:

From @Douglas_Gregor's Swift for C++ Practitioners, Part 1: Intro & Value Types:

Uses of uninitialized variables don't happen in Swift, because of a semantic guarantee called definite initialization : the compiler checks that every variable is initialized before it is used, in all execution paths. This applies equally to all code, and it helps define away a class of bugs that bite us in C++:

Also, can you post the code for the entire class?

Assign "bar" and "extra" first then.

1 Like