Alexito's World

A world of coding 💻, by Alejandro Martinez

UIViewController extension for keyboard avoidance, and the missing features of Swift

Being able to conform to a protocol and automatically have the implementation that you need is really a game changer. Having trait like functionality is one of the most interesting aspects that Swift has given us.

I was playing around (in a playground 😂) to see how protocol extensions could make keyboard avoidance simpler and I came up with a useful extension that you can see in this gist: KeyboardAvoidance.swift.

But I'm still missing some nice things to allow an even more powerful component based programming.

It would be nice to be able to have something like mixins, being able to define stored properties in a protocol. This would allow simplifying the adoption of implementations to just declaring the conformance to the protocol.

Another thing that would be really useful is something like behaviours. In the example, the ViewController that wants to use that protocol still has to call the start method on viewWillAppear for example. It would be nice if the protocol itself could implement that method and define that it wants it to be called after the original implementation is called.

If you liked this article please consider supporting me