Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantage of telling the Swift Compiler an object's type, instead of inferring?

I have been doing Swift programming for a few months now and I have always been curious about this...

Is there an advantage to telling the Swift compiler the type of an object in its declaration? I.e.let image: UIImage = UIImage()

Compared to NOT telling the compiler and having it infer the type at runtime. I.e let image = UIImage()

I would think it would be more efficient to tell the compiler the object type instead of having it infer the type. I know this question appeals to Objective-C syntax as well, so I'll add that in the tags.

like image 247
justColbs Avatar asked Jun 03 '15 15:06

justColbs


People also ask

What is type inference in Swift?

Type inference enables a compiler to deduce the type of a particular expression automatically when it compiles your code, simply by examining the values you provide. Because of type inference, Swift requires far fewer type declarations than languages such as C or Objective-C.

Does Swift use an interpreter or compiler?

An interpreted languages take input and produce output directly however compiled languages first prepares executables and then with according to the data, they produce output. Swift is a compiled language means before producing the actual output Swift perform various activities.

What language is Swift based on?

Apple created Swift, an open-source programming language, as a replacement for all languages based on C, including Objective C, C++, and C. The language was created in 2014 and released to the public as an open-source project in 2015 on Swift.org.


1 Answers

There’s zero runtime efficiency difference between the two. During compilation, Swift is inferring the type and writing it in for you. But once compiled, the two statements are identical.

It’s purely a question of readability and, occasionally, compiler efficiency.

Readability because in the statement let image: UIImage = UIImage(), the double appearance of UIImage is just clutter. And in cases of more complex types, it’s pretty much essential – 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 occasionally you’ll find that a particularly ambiguous type (literals of literals are notorious for this) where lots of overloads need to be resolved can compile a lot faster if you explicitly name the type on the left-hand side. But this is just a question of how fast it compiles, not how fast it runs once it has compiled.

like image 83
Airspeed Velocity Avatar answered Sep 26 '22 02:09

Airspeed Velocity