Sitemap

Dark Side of Swift’s Type Inference

4 min readApr 11, 2024

Swift’s type inference is a powerful instrument that is at the heart of the language’s type safety. As a pleasant side effect, it also allows you omit type annotations when declaring variables. 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.

Not a member? Read here for free.

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 as follows:

struct SomeImplementation: SomeProtocol {

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

}

This is how the types might be used:

let protocolImplementationInstance = SomeImplementation()
protocolImplementationInstance.doSomething()

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

protocolImplementation…

--

--

Nikita Lazarev-Zubov
Nikita Lazarev-Zubov

Written by Nikita Lazarev-Zubov

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

No responses yet