Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift nested structures -- how to access element

In a Swift app, I am attempting to nest structures for greater clarity. Here is the code:

struct ColorStruct {
    var colorname: String = ""
    struct RGB {
        var red:   Int = 0
        var green: Int = 0
        var blue:  Int = 0
    }
}

I can access a ColorStruct element (example: "colorname") as long as it isn't nested.

Q: What am I failing to understanding about how to properly access the "red" variable?

var newColor = ColorStruct()
newColor.colorname = "Red"
newColor.RGB.red   = 255     // Results in error:
// Static member 'RGB' cannot be used on instance of type `ColorStruct`
like image 247
Vic W. Avatar asked Feb 15 '26 23:02

Vic W.


1 Answers

A nested struct as given in the question code doesn't automatically create an outer struct member of that type. To achieve that, refine the code this way:

struct ColorStruct {
  var colorname: String = ""
  struct RGB {
    var red:   Int = 0
    var green: Int = 0
    var blue:  Int = 0
  }

  var rgb = RGB()
}

var color = ColorStruct()
color.rgb.red = 255
like image 141
Max Desiatov Avatar answered Feb 18 '26 19:02

Max Desiatov