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`
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With