This is a tiny syntactic sugar pitch.
Swift's ability to group code by use of extension
is probably one of the best features of Swift and something Apple themselves use a lot, combined with Swift's ability to nest types these two language features make up the backbone of what we love about Swift.
Today extensions are limited to global scope, I cannot extend a nested type within an extension of the enclosing parent type. This makes code hard to read, I would argue.
Simple case study (sorry for made up nonsense types and extensions...)
public struct A {
public let one: One
public let two: One
public let notEncodableEither: NotEncodableEither
public struct One { ... }
public struct Two { ... }
}
Let's say we wanna extent all three types (of which two are nested), today we must write it like this:
// MARK: A Encodable
extension A: Encodable {
public func encode(to encoder: Encoder) throws {
// manually encode `notEncodableEither`
}
}
// MARK: A.One - Encodable
extension A.One: Encodable {
public func encode(to encoder: Encoder) throws {
...
}
}
// MARK: A.Two - Encodable
extension A.Two: Encodable {
public func encode(to encoder: Encoder) throws {
...
}
}
Nothing terribly wrong with this, but it is slightly less clear than, what I propose:
// MARK: Encodable (piched)
extension A: Encodable {
public func encode(to encoder: Encoder) throws {
// manually encode `notEncodableEither`
}
of One: Encodable {
public func encode(to encoder: Encoder) throws {
...
}
}
of Two: Encodable {
public func encode(to encoder: Encoder) throws {
...
}
}
}
The of
label might be omitted if the community does not like it. But it reads out well: "extension of".
This syntax more clearly conveys what is being done here, we make A
and some nested type conform to Encodable, which can now be done in the same extension.
What do you think?