Search code examples
iosswiftinitializationinitializer

Difference between variable declaration and definition in Swift


The terms "declaration" and "definition" are being used synonymously in Apple's Swift documentation and it's getting me confused.

Under the "Initialization" section (which talks about class initializers), Apple states:

You can set an initial value for a stored property within an initializer, or by assigning a default property value as part of the property’s definition.

Further in a subsection they state:

You can set the initial value of a stored property from within an initializer, as shown above. Alternatively, specify a default property value as part of the property’s declaration.

I thought a variable declaration was different than a variable definition.


Solution

  • After doing much searching across the web for legitimate explanations, I have seemed to have found an answer:

    The problem is that the two terms overlap to some extent. Definitions also serve as declarations, because they inject an identifier of a certain type to a scope. However, a declaration isn't a definition because it doesn't entail storage allocation for the declared object. To add to the confusion, the semantics of definitions and declarations is slightly different when applied to types and functions, as I will show momentarily. So let's look at a more detailed analysis of these two terms.

    Here is the article: Declarations and Definitions.

    The article gives further explanation and examples.