Why use extension in the same file as the base object?

I have seen code where a struct is defined and then in the same file an extension for the same struct is defined. Why not just include the contents of the extension in the original struct definition?

There are some circumstances when using an extension to declare something would be required. For example, if you have generic struct and you want to provide a specialized implementation with certain constraints then an extension with a where clause is the way to do that:

struct MyStruct<T> {
  var value: T
}

extension MyStruct where T == Int {
  func addOne() -> Int {
    return value + 1
  }
}

It's more likely, though, that the code you've seen was using extensions as organizational tools. Here are a few examples of when using extensions is not required but might be desirable:

  • If a struct has a lot of members, using extensions can help you group the members of the struct that implement a subsystem or are otherwise related.
  • You might use extensions in the same file to implement conformances to protocols in a nicely organized way, e.g. extension MyStruct: Hashable { /* ... */ }
  • If there is a subset of members on a struct that should share attributes (e.g. @available) then you can use an extension to declare the attributes without duplicating it on each member.
Why use extension in the same file as the base object?
 
 
Q