Posts for Tag: type inference

Being Explicit about Types in Swift

I've just read Andrew Bancroft's post about being explicit about types in Swift which I largely agree with and is worth reading before the rest of this post which adds an extra reason to follow his advice.

Summary of Andrew's Post

Where the type of a declared variable is not immediately visible from the surrounding code such as when it is declared to equal the result of a function, possibly a function defined in another file, you should explicitly declare the type for human readability and understandability purposes even the the compiler is happy inferring the variable's type. I agree with this.

The Other Big Benefit

That post however misses an entire other benefit of the practice which is that you get the compiler to check for you that the type that will be assigned is he one that you expect. If the function you are calling gets changed you will get an error at the call site not where you first use the object of inferred type (if you are lucky - you may get no error at all if the object is used in locations where type is liberal such as string interpolation).

Consider Defining Your Variable as a Superclass or Protocol 

Now it may be possible to declare your variable to a superclass or protocol of the expected object's type and if so that should be done to give some flexibility while ensuring expectations are met. This also documents the flexibility of the type that you can accept. 

Drawback of Explicit Typing

The disadvantage of explicitly typing your object is that if you change what the function that sets it returns and it is still compatible you have to manually change the type (possibly in many places if it is a heavily used function). I think that is a price worth paying to encourage at least a cursory check of the use of the values and to ensure it is not just well typed (which the compiler can do) but also correct.