The compiler does not always know when indirect
is necessary or desired. For example, Optional<T>
is compiled as part of the standard library, and we wouldn't want Optional
to always be indirect
, because that would mean every Int?
or String?
requires an additional allocation to hold the indirect value. Nonetheless, code in another module could attempt to instantiate Optional
in a way that would require indirect-ness to handle recursion:
struct Recursive {
var value: Int
var next: Recursive?
}
By not marking Optional
or its cases indirect
, we explicitly made the choice not to support recursion using Optional because we considered performance to be more important. You use indirect
when you need recursion or want to favor data size over performance. These are judgments for which the compiler can't always make the right choice on its own, so it's up to the programmer to make them.