Inverse inheritance for structs: sub-structs

How much interest is there in adding sub-structs to Swift? I think this could solve one of the problems I've been thinking about.

The idea is that struct inheritance is the opposite of classes: sub-structures have fewer properties than their parent structures, and therefore the memory requirements of sub-structures are less than or equal to their parent. @Joe_Groff mentioned the idea here.

In my specific use case I'm thinking of the Complex number types, which you can imagine has properties real and imag. The idea is then that Real is a sub-structure, where its imag property is always zero.

So now, any function that takes Complex as an argument (like addition), can also handle Real structs as arguments. The advantages could be two-fold,

  • first, a custom override of, e.g., addition for two Real types wouldn't need to add the two (zero) imaginary properties (saving FLOPs), and
  • second, in some cases the compiler might be able to avoid actually allocating that unnecessary memory for the imaginary property if it's never used.

The big problem this solves, that I can't find another work around for, is that one can then write any function that takes two Complex types (or sub-types), performs a bunch of binary operations (addition, multiplication, etc), and returns another Complex type (or sub-type).

Are there other use cases where this would be useful?

Jeffrey

2 Likes