Reputation: 1872
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.
Upvotes: 8
Views: 150
Reputation: 40955
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.
Upvotes: 10
Reputation: 71854
From Swift Documentation:
It is rare that you need to write type annotations in practice. If you provide an initial value for a constant or variable at the point that it is defined, Swift can almost always infer the type to be used for that constant or variable, as described in Type Safety and Type Inference
So It doesn't matter if you declare instance type or not.
Upvotes: 2