Reputation: 837
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`
Upvotes: 3
Views: 6370
Reputation: 13033
This line:
struct RGB{ var red: Int = 0}
states that red is an instance variable in a struct RGB
(with other words, red does belong to an instance of RGB). When you create a struct of type ColorStruct, you do not create a struct RGB
. You can only access instance variabele if you have created an object of it. If you want to access the variabele red, create a struct RGB (RGB()
), or make the variabele/struct (is this possible in Swift?) static (don't make it an instance variabele).
Upvotes: 2
Reputation: 21144
You cannot assign value to struct just like that. Either create a new property of RGB like so,
struct ColorStruct {
var colorname:String = ""
var rgb = RGB()
struct RGB {
var red: Int = 0
var green: Int = 0
var blue: Int = 0
}
}
var newColor = ColorStruct()
newColor.colorname = "Red"
newColor.rgb.red = 255 // Results in error:
Or, make static variable inside ColorStruct,
struct ColorStruct {
var colorname:String = ""
static var rgb = RGB()
struct RGB {
var red: Int = 0
var green: Int = 0
var blue: Int = 0
}
}
ColorStruct.rgb.red = 255
Upvotes: 1
Reputation: 630
You must instantiate your RGB
struct instead of ColorStruct
:
struct ColorStruct {
var colorname:String = ""
struct RGB {
var red: Int = 0
var green: Int = 0
var blue: Int = 0
}
}
var newColor = ColorStruct.RGB()
newColor.red = 255
Upvotes: 0
Reputation: 5565
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
Upvotes: 6
Reputation: 2913
You can achieve it by this:
struct ColorStruct {
var colorname:String = ""
var colorValue: RGB!
struct RGB {
var red: Int = 0
var green: Int = 0
var blue: Int = 0
mutating func setRed(value: Int) {
self.red = value
}
mutating func setGreen(value: Int) {
self.green = value
}
mutating func setBlue(value: Int) {
self.blue = value
}
}
}
And then use the struct as:
var color = ColorStruct()
color.colorname = "blue"
color.colorValue = ColorStruct.RGB.init(red: 0, green: 0, blue: 1)
print(color.colorValue)
And if you want to change a value call this :
color.colorValue.setRed(value: 2)
print(color.colorValue)
Hope it helps
Upvotes: 0