On Aug 16, 2024, at 10:17, Larry Garfield <[email protected]> wrote:
>
> I would have to research to see if other languages did this, but one option
> would be to allow an inner class to extend an outer class even if it's final,
> which would essentially give us sealed classes for free:
>
> final class Outer
> {
> class InnerA extends Outer {}
> class InnerB extends Outer {}
> class InnerC extends Outer {}
> }
>
> // But this is still not OK:
> class Sibling extends Outer {}
>
> Note: I have no idea how difficult/complicated this would be, but I would be
> in favor of exploring it.
>
> --Larry Garfield
Swift allows nested classes to extend their parent. It does not allow nested
classes to extend a final parent. Visibility modifiers can be applied and work
as expected. Basically, types also function as the equivalent of a namespace.
More broadly, any type can be nested in any other type, so you could certainly
do something weird like:
```
class A {
enum E {
class C: A {}
case a(A)
case c(C)
}
}
let e = A.E.c(A.E.C())
```
However, you could implement your sealed class example by having a private
constructor:
```
class Parent {
final class Child : Parent {
override init() { //within lexical scope of Parent, so can see
Parent's private members
super.init()
}
}
private init() {}
}
let parent = Parent() //'Parent' initializer is inaccessible due to 'private'
protection level
let child = Parent.Child() //ok
```
Swift also has a fileprivate visibility, so the same could be accomplished with
a fileprivate init on Parent with a non-nested Child in the same file.
-John