Shades Shades - 1 year ago 101
Swift Question

Extensions in my own custom class

I was reading through another SO question, Swift do-try-catch syntax. In his answer, rickster creates an extension for the OP's custom class. Konrad77 comments that it's a "Really nice way to keep your code clean." I respect their knowledge which leads me to believe I'm missing the point somewhere in my own code.

Are any other benefits (aside from cleanliness) or reasons to create an extension for a class I created? I can just put the same functionality directly into the class. And does the answer change if I am the only one using the class or if someone else will be accessing it?

Answer Source

In the case of a class that you create from scratch extensions are a powerful type of documentation through structure. You put the core of your class in the initial definition and then add on extensions to provide additional features. For example, adding adherence to a protocol. It provides locality to the contained code:

struct Foo {
  let age: Int

extension Foo: CustomStringConvertible {
  var description:String { return "age: \(age)" }

Could I have put the protocol and computed property in the struct declaration? Absolutely but when you have more than one or two properties it starts to get messy and difficult to read. It's easier to create bugs if the code isn't clean and readable. Using extensions is a great way to stave off the difficulties that come with complexity.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download