Reputation: 1165
In swift Programming language constants can expressed with let keyword like this
let MyConstant = 100
and implicitly defined with type name like below
let MyConstant: Int = 100
what are the benefit of using second method?
Upvotes: 2
Views: 403
Reputation: 26652
The compiler infers the type to save you - the developer - time. Why specify it when it's obvious from the value? Assuming it is obvious. I'll come to that shortly.
So if you can if you want to, what's the point? (no pun intended)
Perhaps for clarity; you wish to make it absolutely clear that the type of the variable is to be Int
. The other purpose is that - in some cases, e.g. floating point types - the compiler's inferred default may not be what you desired. For example:
let MyConstant = 100.0
Double or Float? It assumes Double. If you want Float, you must be explicit:
let MyConstant: Float = 100.0
See The Swift Programming Language: Types:
In Swift, type information can also flow in the opposite direction—from the root down to the leaves. In the following example, for instance, the explicit type annotation (: Float) on the constant eFloat causes the numeric literal 2.71828 to have type Float instead of type Double.
let e = 2.71828 // The type of e is inferred to be Double.
let eFloat: Float = 2.71828 // The type of eFloat is Float.
Type inference in Swift operates at the level of a single expression or statement. This means that all of the information needed to infer an omitted type or part of a type in an expression must be accessible from type-checking the expression or one of its subexpressions.
Upvotes: 3