-2
struct Shape{
var length: Float = 0
var width: Float = 0

struct Rectange {
    var length = Shape().length
    var width = Shape().width

    var area: Float{
        get{
            return length * width
        }
    }


}   
}

I know how to assign values from one struct to a nested struct. I just want to see if this IS USED or "LEGAL" in real life.

2 Answers2

1

Yes, this approach is used in real life.

Look at this example (here I'm using an enum but we can imagine similar examples for structs and classes)

struct Spaceship {
    enum Speed {
        case warp, light
    }
    let maxSpeed: Speed
}

struct Airplane {
    enum Speed {
        case subsonic, supersonic
    }
    let maxSpeed: Speed
}

Both structs have a Speed type defined inside them. Since the Speed enum is defined inside the namespace of Spaceship and Airplane there is no naming collision and everything is pretty clear.

Luca Angeletti
  • 58,465
  • 13
  • 121
  • 148
  • Okay, I sort of see where your heading. My example is like if you have a type `Shape` , type `Rectangle`, and type `Square`. That would also make sense to put those two types inside `Shape`? @appzYourLife – FusionPointInc Oct 29 '16 at 18:55
  • @FusionPointInc: I updated my answer, please take a look. – Luca Angeletti Oct 29 '16 at 19:07
  • Yeah I understand, but I mean't if you placed that Airplane under Spaceship, is that still practiced? It doesn't matter if you have values or not. – FusionPointInc Oct 29 '16 at 19:09
1

It is definitely used in real life. Apple even recommends this in one of their sample code examples. https://developer.apple.com/library/content/LucidDreams/Introduction/Intro.html

Thomas Abend
  • 368
  • 3
  • 13
  • It would make sense to have type `Shape`, type `Rect`, and type `Circle` and place `Rect` and `Circle` under `Shape`? – FusionPointInc Oct 29 '16 at 18:59
  • Well, that would depend on what you were trying to do. The advantage of nesting these types is that it is sometimes easier to reason about things in this way. In that sample code you see a lot of enums that are defined within classes because they are used within those classes. I'm not sure if your case fits that. – Thomas Abend Oct 29 '16 at 19:00