Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper syntax for accessing a struct variable?

Tags:

struct

swift

What is the proper syntax for access a member struct variable? I'm currently trying like this:

struct one {
    var name:String = "Ric"
    var address:String = "Lee"
}

one.name

But the last line produces the error:

'one.Type' does not have a member named 'name'

How can I access the variable on my struct?

like image 206
Frederick C. Lee Avatar asked Oct 18 '14 21:10

Frederick C. Lee


People also ask

How do you access structure variables?

Array elements are accessed using the Subscript variable, Similarly Structure members are accessed using dot [.] operator. Structure written inside another structure is called as nesting of two structures.

What is the syntax of structure?

Syntax to Define a Structure in CstructName: This is the name of the structure which is specified after the keyword struct. data_Type: The data type indicates the type of the data members of the structure. A structure can have data members of different data types.

How do you declare a structure variable?

A "structure declaration" names a type and specifies a sequence of variable values (called "members" or "fields" of the structure) that can have different types. An optional identifier, called a "tag," gives the name of the structure type and can be used in subsequent references to the structure type.

What is structure variable?

Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. Unlike an array, a structure can contain many different data types (int, float, char, etc.).


1 Answers

It looks like you defined a struct, but didn't create an instance of it. If you create an instance, you can access its name and address properties.

struct one {
    var name: String = "Ric"
    var address: String = "Lee"
}
var x = one()
x.name

It may be confusing because you can set default values in the definition, which may make it look like you are instantiating something.

like image 121
Connor Avatar answered Sep 21 '22 20:09

Connor