Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access a struct nested inside a struct

Tags:

I've created a struct with another struct nested inside of it, like this:

struct Theme {     var ID: Int     var name: String     struct color {         var tint: String         var tintDisabled: String         var accent: String         var background: String         var items: [String]     } } 

I thought I'd be able to address the "tint" item like this:

aTheme.color.tint 

But aTheme doesn't have a member "color".

How can I get at it? Or is this just no-go and I should use a different structure?

like image 549
Matthew Frederick Avatar asked Mar 29 '15 06:03

Matthew Frederick


People also ask

How do I access nested structs?

To access the members of the inner structure, we write a variable name of the outer structure, followed by a dot( . ) operator, followed by the variable of the inner structure, followed by a dot( . ) operator, which is then followed by the name of the member we want to access.

How do you access members of nested structures explain with example?

stuct emp{ int eno; char ename[30]; float sal; struct allowance{ float da; float hra; float ea; }a; }e; The inner most member in a nested structure can be accessed by changing all the concerned structure variables (from outer most to inner most) with the member using dot operator.

Can a structure be nested inside a structure?

A nested structure in C is a structure within structure. One structure can be declared inside another structure in the same way structure members are declared inside a structure.

How do you access structure members?

Structure members are accessed using dot (.) operator.


1 Answers

What you've created is a nested typecolor is declared as a type inside the Theme type, so to create an instance of color you would use this notation:

let myColor = Theme.color( ... ) 

I think instead you want a property of a Theme instance to be a color instance. For this you don't need the types to be nested:

struct Color {     var tint: String     var tintDisabled: String     var accent: String     var background: String     var items: [String] }  struct Theme {     var ID: Int     var name: String     var color: Color } 

Note: Types should always be declared with initial caps.

like image 160
Nate Cook Avatar answered Sep 18 '22 19:09

Nate Cook