The advantage is to tell the Swift Compiler the type of the object, rather than displaying it?

I have been involved in Swift programming for several months now, and I was always curious about this ...

Does it make sense to tell the Swift compiler the type of an object in its declaration? Those. let image: UIImage = UIImage()

Compared to NOT telling the compiler and keeping in mind the type at run time. Ie let image = UIImage()

I would have thought that it would be more efficient to tell the compiler the type of an object, rather than outputting it. I know this question refers to Objective-C syntax, so I will add this to the tags.

+8
ios variable-declaration swift
source share
2 answers

Performance difference from zero. At compile time, Swift infers the type and writes it for you. But after compilation, both statements are identical.

This is solely a matter of readability and, sometimes, compiler efficiency.

Readability, as in the expression let image: UIImage = UIImage() double view of UIImage is simply messy. And in the case of more complex types, this is very important - no one wants to write let keys: LazyForwardCollection<MapCollectionView<Dictionary<String, Int>, String>> = dict.keys , when they can write let keys = dict.keys .

Compiler efficiency, because sometimes you find that a particularly ambiguous type (literal literals are known for this), where many overloads need to be resolved, can be compiled much faster if you explicitly name the type on the left side. But this is just a question of how quickly it compiles, not how quickly it starts after compiling it.

+10
source share

From Swift Documentation :

Rarely have to write type annotations in practice. If you specify the initial value of a constant or variable at the point at which it is defined, Swift can almost always output the type that will be used for this constant or variable, as described in Security type and type input

So it doesnโ€™t matter if you declare an instance type or not.

+2
source share

All Articles