The Dao of Protocol Extensions in Swift Part 1

Most of us probably have known how to use self-run closure to help property initializing and keep related code self-contained.

Let’s move a little forward. Type inference is Swift natural ability, and thanks for it, developers just need input Type only once in most places. And here, how about eliminating the extra declaration of UILabel?

From NSHipster, I learned a useful public function. And I improve it slightly (Maybe you disagree).

👍It’s great, but I should never stop think forward. After many years coding, I’ve became addicted into those massive utilities with inertia. But another man in brain tells me it’s not elegant. Why copy so many thinkings from C without second thoughts? After all, Swift has tons of wonderful language features, such as Extension and Protocol. Why not swift natively.😎

Extend the World’s Entities

So let’s extend all objects, not just only the UILabel.

Ops, we have to use NSObject to replace ‘Self’ here, but lost the sub Type information. It means we have to use the annoying as! or as? in next place. It’s getting even worse.😰

Extend the World using Dao

Extension conflicts with ‘Self’ when extending Entity, but you know Protocol in Swift welcomes ‘Self’. I wish I’m the last person on the earth known it.

In Chinese culture, Dao describes a fairyland where nothing is everything, everything is nothing. It’s empty but rich, it’s still but transformable.

Don’t be scared, Dao is just an analogy for me to understand strange things easily.

How about use Dao transform logic features into entities?

Dao really works👏

Extend sub-World using Dao

But stop being visionary with Dao and face up to reality.

Obviously, we lose UIButton(type:) convenience initializer. This world is extraordinarily complex, never under the delusion of done once and for ever. Let’s try to use Dao again in sub-world of UIButton.

By adding constraints to protocol extensions for UIButton sub-set of NSObject, it works. This pattern seems damn cool. But be careful exceed too much to fire yourself.

BTW, Thanks for the simplify of function calling. we successfully eliminate the ( ) after UIButton. It’s elegant, too much.

Multiple Config Closures

Thanks for all the scrolling patiently. Let’s think forward one more. If you enjoy it, please give this story a big star.

Honestly, I refuse this coding style. Just a joke to show how strong Swift is, have fun.


Writing in NZ earthquake. I’m good, thanks.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.