Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a struct variable inside a class

I have a struct variable that is wrapped into an NSObject class.

Here is how it looks:

class myClass: NSObject{

struct myStruct {
    var array1: [String]
    var additionalInfo: String?
    var array2: [String]
}

var myVar = [myStruct(array: ["value1"], additionalInfo:nil, array2: ["value1","value2"])]
}

My goal is to append the myVar variable with values from a different class and to access them.

I'm trying this code for appending:

var classAccess = myClass()
classAccess.myVar.append(array1:["value 3"], additionalInfo:nil, answers:["value 3"])

However, I get all sorts of nasty errors when I try to compile.

How do you access it the proper way?

like image 924
David Robertson Avatar asked Nov 02 '15 20:11

David Robertson


People also ask

Can we use struct inside class?

Yes you can. In c++, class and struct are kind of similar. We can define not only structure inside a class, but also a class inside one. It is called inner class.

How do you access struct values?

Accessing data fields in structs Although you can only initialize in the aggregrate, you can later assign values to any data fields using the dot (.) notation. To access any data field, place the name of the struct variable, then a dot (.), and then the name of the data field.

Can you use struct in class C++?

The C++ class is an extension of the C language structure. Because the only difference between a structure and a class is that structure members have public access by default and class members have private access by default, you can use the keywords class or struct to define equivalent classes.


1 Answers

You can do that, but you have to use the MyStruct initializer and you have to reference the struct from outside the class with MyClass.MyStruct

class MyClass: NSObject{

  struct MyStruct {
    var array1: [String]
    var additionalInfo: String?
    var array2: [String]
  }

  var myVar = [MyStruct(array1: ["value1"], additionalInfo:nil, array2: ["value1","value2"])]
}


var classAccess = MyClass()
classAccess.myVar.append(MyClass.MyStruct(array1:["value 3"], additionalInfo:nil, array2:["value 3"]))

Note: for better readability I capitalized the struct and class names

like image 198
vadian Avatar answered Oct 23 '22 04:10

vadian