Difference between variable declaration and definition in Swift - ios

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.

You are right that those two mean different thing, THOUGH I think most of the people just use both of them in the same meaning and I think that is also the case of those AppleDocs. Here is great article on subject:
Summary
A declaration provides basic attributes of a symbol: its type and its
name. A definition provides all of the details of that symbol--if it's
a function, what it does; if it's a class, what fields and methods it
has; if it's a variable, where that variable is stored. Often, the
compiler only needs to have a declaration for something in order to
compile a file into an object file, expecting that the linker can find
the definition from another file. If no source file ever defines a
symbol, but it is declared, you will get errors at link time
complaining about undefined symbols.

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.

Declaration of variable mean to tell compiler their is a var\funct\struct of particular data type. Definition of variable mean asking compiler to allocate memory to variable or define storage for that variable. you can define a variable only one time but you can declare it as many time you want.

I think Apple's Swift 4 Language Reference can be construed as the authoritative answer. From the Declarations section (emphasis mine):
A declaration introduces a new name or construct into your program.
For example, you use declarations to introduce functions and methods,
variables and constants, and to define new, named enumeration,
structure, class, and protocol types. You can also use a declaration
to extend the behavior of an existing named type and to import symbols
into your program that are declared elsewhere.
In Swift, most declarations are also definitions in the sense that
they are implemented or initialized at the same time they are
declared. That said, because protocols don’t implement their members,
most protocol members are declarations only. For convenience and
because the distinction isn’t that important in Swift, the term
declaration covers both declarations and definitions.

Related

If a set literal is of type set then what is its class in dart?

So the following code snippet
Set mySet = {1,2,3};
is an instance of type Set which is permissible, however what would the class of the set literal be. I have tried to search for this, however I have found no answer in the dart documentation.
A literal exists only in your source code. Asking for its "class" doesn't make a lot of sense.
Using a Set, Map, or List literal is just syntactic sugar for invoking a corresponding constructor. The Set factory constructor constructs a LinkedHashSet.
However, you'll see that LinkedHashSet is also abstract. Its factory constructor returns an instance of a private, internal class. You can see its typename via print(Set().runtimeType); the actual type might be different for different platforms and is unlikely to be useful to you.

should I give type?

Should I give type when creating variable?
Any downside for just declaring the keyword "var"?
Any difference between these two?
var a = 0;
int a = 0;
Pros/Cons
ONGOING WORK
Best Practices
It's recommended to use var or final keyword, without specifying type annotation, and implicitly infer type for known local variables. Otherwise it's recommended to specify type annotations. As for dynamic keyword, it should be used very sparingly in specific use-cases, when you're doing manual type checking. For example print(myVariable is SomeType).
omit_local_variable_types Dart linter rule encourages omitting type annotation for known local variables. always_specify_types encourages specifying type annotations for cases that don't fall into the scope of the former linter rule.
1. Style guide for Flutter repo
1.1 avoid using var
All variables and arguments are typed; avoid "dynamic" or "Object" in
any case where you could figure out the actual type. Always specialize
generic types where possible. Explicitly type all list and map
literals.
This achieves two purposes: it verifies that the type that the
compiler would infer matches the type you expect, and it makes the
code self-documenting in the case where the type is not obvious (e.g.
when calling anything other than a constructor).
Always avoid "var". Use "dynamic" if you are being explicit that the
type is unknown, but prefer "Object" and casting, as using dynamic
disables all static checking.
2. Dart Lint Rules
2.1 omit_local_variable_types
CONSIDER omitting type annotations for local variables.
Usually, the types of local variables can be easily inferred, so it
isn't necessary to annotate them.
2.2 always_specify_types
DO specify type annotations.
Avoid var when specifying that a type is unknown and short-hands that
elide type annotations. Use dynamic if you are being explicit that the
type is unknown. Use Object if you are being explicit that you want an
object that implements == and hashCode.
References
You can refer to Style guide for Flutter repo, full list of Dart's Linter Supported Lint Rules, and Effective Dart's Style Guide.
Note, Style guide for Flutter repo is used among flutter community and takes precedence over LinterRules and Effective Dart's Style Guide especially within repo contributions. From what I've seen, Style guide for Flutter repo is more of a superset Style Guide that should honor Dart Linter rules.
There isn't any difference between the two statements you gave.
And I don't see any downside to only declare the keyword "var", unless that your code might become a bit more difficult to read. On the other side, specifying the type might become a bit redundant sometimes.
But this is really just a question of taste 😄
I advise you to pick between those two, and be consistent in your code.
If you choose to always specify the type, you can use always_specify_types in your file analysis_options.yaml :
https://dart-lang.github.io/linter/lints/always_specify_types.html

How does inlining work with external libraries? (Swift)

The attribute #inline(__always) forces the compiler to inline a particular function. How is code provided by external libraries inlined in one's project? Does the compiler actually copy code segments from the library's executable?
As far as I'm aware, #inline(__always) means that the function (or similar) is always inlined, no matter what. That means that its symbols are exposed in the compiled module so they can be inlined by projects consuming that module. Hence the "always".
This is largely an undocumented attribute, with the only official references I can find being in some stdlib devs' internal documentation, not even describing its behavior directly. The best unofficial documentation I can find is Vandad Nahavandipoor's disassembly-confirmed investigation into its behavior, which doesn't attempt to confirm the cross-module use case you are concerned with.
In Swift 4.2, #inlinable and #usableFromInline were introduced to finish this story.
My understanding:
#inline(__always) forces functions (et al) to be inlined every time no matter where they're declared or used
#inlinable allows functions (et al) in a module to be inlined into calling code in that module, or calling code using that module, if the compiler deems it necessary
#usableFromInline allows functions (et al) internal to a module to be inlined into #inlinable calling code that's also in that module, if the compiler deems it necessary. Unlike #inlinable, these must be internal; they cannot be public
According to Swift.org:
inlinable
Apply this attribute to a function, method, computed property, subscript, convenience initializer, or deinitializer declaration to expose that declaration’s implementation as part of the module’s public interface. The compiler is allowed to replace calls to an inlinable symbol with a copy of the symbol’s implementation at the call site.
Inlinable code can interact with public symbols declared in any module, and it can interact with internal symbols declared in the same module that are marked with the usableFromInline attribute. Inlinable code can’t interact with private or fileprivate symbols.
This attribute can’t be applied to declarations that are nested inside functions or to fileprivate or private declarations. Functions and closures that are defined inside an inlinable function are implicitly inlinable, even though they can’t be marked with this attribute.
usableFromInline
Apply this attribute to a function, method, computed property, subscript, initializer, or deinitializer declaration to allow that symbol to be used in inlinable code that’s defined in the same module as the declaration. The declaration must have the internal access level modifier. A structure or class marked usableFromInline can use only types that are public or usableFromInline for its properties. An enumeration marked usableFromInline can use only types that are public or usableFromInline for the raw values and associated values of its cases.
Like the public access level modifier, this attribute exposes the declaration as part of the module’s public interface. Unlike public, the compiler doesn’t allow declarations marked with usableFromInline to be referenced by name in code outside the module, even though the declaration’s symbol is exported. However, code outside the module might still be able to interact with the declaration’s symbol by using runtime behavior.
Declarations marked with the inlinable attribute are implicitly usable from inlinable code. Although either inlinable or usableFromInline can be applied to internal declarations, applying both attributes is an error.

Properties in Categories

Why is it allowed to declare properties in categories when neither they nor their accessor methods are synthesized? Is there any performance overhead involved?
Is categorisation purely a compiler technique?
I'm trying to understand how categories work. This just explains what to do and what not to do. Are there any sources which go into more detail?
EDIT : I know that I can use associated references. Thats not what I'm asking for. I want to know why are the properties not synthesised? Is there a performance issue or a security issue if the compiler synthesises them? If there is I want to know what and how?
Why is it allowed to declare properties in categories [...] ?
Properties have many aspects (during compile- and runtime).
They always declare one or two accessor methods on the class.
They can change the selector when the compiler transforms dot notation to messages.
In combination with the #synthesize directive (or by default) they can make the compiler synthesize accessor methods and optionally ivars.
They add introspection information to the class which is available during runtime.
Most of these aspects are still useful when declaring properties in categories (or protocols) and synthesizing is not available.
Is categorisation purely a compiler technique?
No. Categories, as properties, have both compile time as well as runtime aspects.
Categories, for example, can be loaded from dynamic libraries at a later time. So there might already be instances of a class that suddenly gets new methods added. That's one of the reasons categories cannot add ivars, because old objects would be missing these ivars and how should the runtime tell if an object has been created before or after the category has been added.
Before you go into categories, please reconsider the concept of properties in Obj-C: A property is something you can write and read to in an abstract sense, using accessors. Usually, there is an instance variable assigned to it, but there is no need to do so.
A property may also be useful e.g., to set a number of different instance variables in a consistent way, or to read from severals variables or do some calulation.
The crucial fact here: there is no need to have an instance variable assigned to a property.
A category serves as an extensiton of an object's behavior, i.e., to extend its set of methods, without changing the data. If you see a property in it abstract sense, then it add accessors, thus it matches the idea of a category.
But if you synthesize it, an instance variable would be generated what contradicts the idea of a category.
Thus, a property in a category makes only sense if you use it in the uncommon, abstract way, and #synthesize is to ease the common way.
You may want to read NSHipster about how to implement properties storage in categories.
Quoting from the article: "Why is this useful? It allows developers to add custom properties to existing classes in categories, which is an otherwise notable shortcoming for Objective-C."
#synthesize informs the compiler to go ahead and provide a default implementation for the setter and the getter.
Said default setters/getters rely on the existence of some kind of storage inside the object.
Categories do not offer any extra storage, so default setters/getters would have no place to store into, or read from.
An alternative is to use:
#dynamic
and then provide your own implementation and own storage for the said properties.
One way is to use associated objects.
Another would be to store into/read from some completely unrelated place, such as some accessible dictionary of NSUserDefaults or ...
In some cases, for read only properties, you can also reconstruct/compute their values at runtime without any need to store them.

Are "class var"s initialized to zero?

I know that, in Delphi, instance variables and global variables are initialized to zero (this has been asked here before).
However, what about static variables (class var)? I would expect class vars to be initialized to zero, just like global variables. But I've seen too many new Delphi compiler features that were still half-baked to assume that it works, without documentation that actually states a guarantee.
The Help has no index entry for "class var". The "Fields" topic mentions class fields, but does not specify whether they're initialized at program startup. And the obvious fix, of explicitly initializing them (class var X: Integer = 0;), doesn't compile ("';' expected but '=' found").
Are class variables initialized to zero? Is there documentation that explicitly states this?
I'm not aware of any documentation that explicitly states it, but class vars are just a special type of global variable, and globals get zeroed.

Resources