Extensions in my own class

I read another SO question, Swift do-try-catch syntax . In its answer, rickster creates an extension for the custom class OP. Konrad77 notes that this is "a really good way to keep the code clean." I respect their knowledge, which makes me believe that I am missing a point somewhere in my own code.

Are there any other advantages (other than cleanliness) or reasons for creating an extension for the class I created? I can just put the same functionality directly into the class. And will the answer change if I'm the only one using the class, or if someone else gets access to it?

+1
swift
Mar 28 '16 at 13:58
source share
1 answer

In the case of a class created 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 extensions to provide additional functions. For example, adding protocol attachment. It provides the locality of the contained code:

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

Can I put a protocol and computed property in a structure declaration? Absolutely, but when you have more than one or two properties, it starts to become dirty and difficult to read. It is easier to create errors if the code is not clean and readable. Using extensions is a great way to deal with difficulties that arise with complexity.

+5
Mar 28 '16 at 14:19
source share



All Articles