Extensions in my own custom class

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.

Leave a Comment