Frederick C. Lee
Frederick C. Lee

Reputation: 9503

What is the proper syntax for accessing a struct variable?

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?

Upvotes: 9

Views: 12324

Answers (2)

Connor
Connor

Reputation: 64644

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.

Upvotes: 11

Antonio
Antonio

Reputation: 72760

When you declare a struct, in order to use it you have to create an instance. The one struct is a type, just like Int is a type and in order to use it you have to create a variable of Int type:

var myInt:Int = 10

Similarly, once you define a struct, you can create instances of that struct and assign to a variable:

var myStruct = one()

at that point you are able to access to instance properties and methods:

println(myStruct.name)

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

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

and that's the only case when you can reference properties and invoke methods using the type and not an instance of the type:

println(one.name)

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

Upvotes: 5

Related Questions