Swift: Making the Associated Type Parameter Readable in Protocols

I’m still getting used to Associated Types in Swift. Even though they’ve been around for a while, I first starting to understand them from this talk by @alexisgallagher.

So I was happy yesterday when I used them to sort of solve a common problem in iOS development: View Controller Data Injection with Storyboards and Segues in Swift.

I updated my blog post from yesterday, but my initial Protocol looked something like this:

Notice the thing! Since each View Controller would be injected with something specific – it could be text-based or number-based or array-based, anything! I didn’t know how to name the parameter. So thing seemed like the most fitting parameter name.

The implementation was something like this then:

I didn’t exactly like the whole thing here – it’s not that great with readability. So this morning, I though of a crazy solution for this, tried it out, and it actually worked!

Instead of using thing, I leave the parameter name blank in the protocol!

Apparently, this now let’s me name the parameter anything I want in the implementation!

Now, the implementation is super clear! The more I use associated types, the more I like them!

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.