Dark Side of Swift’s Type Inference

Nikita Lazarev-Zubov
4 min readApr 11, 2024

Swift’s type inference is a powerful instrument that lies in the base of the language’s type safety. As a pleasant side effect, it also allows you omit types when declaring variables. In most cases. Sometimes, however, it might lead to degradation of the design of your code. Let’s look at a few pitfalls that come with the language feature.

Type Inference as Encapsulation Breaker

We all love hiding our classes behind interfaces and use protocols a lot. And why not? It helps testability and encapsulation, it separates the interface from implementation details. But there’s a catch there. Consider the following declaration:

protocol SomeProtocol {
func doSomething()
}

And a protocol implementation with some additional methods:

struct SomeImplementation: SomeProtocol {

func doSomething() { }
func doSomethingElse() { }

}

This is how the declarations might be used:

let protocolImplementationInstance = SomeImplementation()
protocolImplementationInstance.doSomething()

However, nothing prevents us to use extra functionality of the implementing type:

protocolImplementationInstance.doSomethingElse()

--

--

Nikita Lazarev-Zubov

Swift and general programming topics, Agile software development, soft skills