What is the correct syntax for accessing a structure variable?

What is the correct syntax for accessing a member variable? I am currently trying to do the following:

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

But the last line throws an error:

'one.Type' has no member named 'name'

How can I access a variable in my structure?

+5
source share
2 answers

It looks like you defined the structure, but did not 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 

This can be confusing because you can set default values ​​in the definition, which can make it look like you are creating something.

+6
source

When you declare a structure in order to use it, you need to create an instance. The one structure is a type, just as Int is a type, and to use it you need to create an Int type variable:

 var myInt:Int = 10 

Similarly, once you define a structure, you can instantiate this structure and assign a variable:

 var myStruct = one() 

at this point you can access the properties and methods of the instance:

 println(myStruct.name) 

If you don't need an instance instead, you must declare the properties and methods as static :

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

and that the only case where you can refer to properties and call methods using a type, not an instance of a type:

 println(one.name) 

Side note: by convention, classes and struct (and, more commonly, any type) should be named with the first character in uppercase.

+2
source

Source: https://habr.com/ru/post/1204990/


All Articles