Swift: Configuring a Constant Using Shorthand Argument Names

There is a tweet going around on initializing constants in Swift using positional references:

The original code is here.

Since it is an ephemeral tweet, and I was confused when it didn’t work as I expected on first glance, I wanted to write a more permanent blog post on the topic here.

The Problem

It’s a common pattern in Swift (and a really nice one!) to configure constants right when they are initialized in a closure vs later on in a viewDidLoad or another such method:

I’ve always found it kind of awkward to name another UIView in the closure. Now there is a “purpleView” and a “view”. Should “view” actually be named “purpleView” also? I haven’t figured out a good solution for the naming problem here.

The Solution

So I was super excited to see the tweet that uses $0 instead of bothering to name the variable! I immediately tried it like this:

But it didn’t work… Upon closer inspection of @ericasadun’s code, I learned that I had to pass in the initialized UIView when the closure is executed:

This of course makes a lot of sense!

Conclusion

I do really like the idea of using $0 here instead of explicitly naming the thing, but I’m upset that it didn’t come naturally to me. However, now that I know I have to pass in an initialized UIView() in there, it does logically make sense. I think I’ll use this in the future. Getting to use $0 here is just too beautiful not to!

Join me for a Swift Community Celebration šŸŽ‰ in New York City on September 1st and 2nd. Use code NATASHATHEROBOT to get $100 off!

Update

As @khanlou pointed out, there is a super cool library called Then to make this even more readable and better:

While I’m not a fan of adding this library as a dependency to my project, @khanlou pointed out once again that it’s only 15 lines of code. So I’ll definitely consider copying this over manually into my project!

Make sure to also check out @ericasadun’s nice solution!

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