1

Possibly a silly question but, other than classes, structs, enums, and protocols that you don't have access to. What would be a significant reason for you to create an extension for a class( structs, enums, and protocols )you have created?

curiously77
  • 225
  • 1
  • 4
  • 24
  • 3
    Clarity. Organization. Neatness. Style. Also protocol extensions have special powers. – matt Aug 29 '19 at 19:25
  • Thanks @matt I was thinking that but I was wondering if there was like something super awesome that I am missing. haha – Xavier James Shelton Aug 29 '19 at 19:27
  • 1
    @XavierJamesShelton Well, you can't define an initializer within a struct declaration without replacing the default member-wise initializer. If you define your custom initializers in an extension, and keep the main declaration free of any initializers, you get to keep the default member-wise initializer, and also have your custom ones, too. This is really handy for introducing new "convenience initializers" (although they're not formally called that, for structs), which delegate to the member-wise one. It's not the best design, but it's a quirk of the language as it is today – Alexander Aug 29 '19 at 19:50
  • Oh that's pretty cool Thank you @Alexander – Xavier James Shelton Aug 31 '19 at 18:46

2 Answers2

2

It's easier to maintain a codebase where protocols agreements are separated, you can quickly find what you're looking for, you can even separate them on specific files to separate even more.

Imagine searching lots of methods to find specific matching rules, that would be an unnecessary effort.

Technically you can do everything on the class with no extensions, but you have the possibility to separate them the way you want to.

Gustavo Vollbrecht
  • 3,188
  • 2
  • 19
  • 37
  • Thank you so much. That seems like a very smart way to keep your code clean. I was very confused about why the documentation was like create an extension for your own class and I was like but WHY?! – Xavier James Shelton Aug 29 '19 at 19:31
1

A lot of times you have protocols that you need to conform to, and you don’t want to list all of them at the top of a class since it’s much less organized. Extensions allow you to easily keep track of and categorize any delegate methods you write so when something breaks you can easily make the fix without searching through your code.

You could of course just organize your code via pragma marks but many people feel it doesn’t look as nice and you lose the benefit of not having to list all the protocols you’re confirming too at the top of the class.

Mike
  • 1,471
  • 12
  • 17