Bookshelves in the Study

Ever since I was little, bookshelves have dominated my rooms. I had built-in bookshelves that my dad made for me when we moved to the house I grew up in. I quickly filled them with all kinds of books…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Using Self in Swift Class Extensions

It might be tempting to use Self as a parameter type when extending classes but Swift only allows it in a protocol or as the result of a class method invocation.

In fact, this is a semantically correct restriction for non-final classes in most cases, except when we want to use Self as an argument of the closure, think about completion handlers for example. In that case Self is used just as an another method call result which is absolutely valid option.

‘Self’ is only available in a protocol or as the result of a method in a class 😕

My favorite example here is the continuation helper for the Operation class:

So we need to pass a block receiving operation that has just finished execution as a parameter. That is not allowed in a class extension.

Hm, but we can use Self that way in a protocol, right… Protocols to the rescue! The plan is to define a dummy protocol, conform our class to it and extend the protocol instead of the class.

Now we can use our continue(on:with:) extension and access operation result in a type-safe manner:

Thanks for your time and hope this writing was useful for you. Please don’t forget to 💚 if you found this article useful.

Add a comment

Related posts:

Waste Management

Trash is the tragedy of human life on this planet. The day we control it in a managed methodology, will be the day we can call ourselves an important part of mother nature. Trash can travel across…