Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Variable name in dot notation in Swift

I want to use variable names in dot notation in Swift.

I’m wrestling with trying to make sense of JSON in Swift, and having a really hard time doing things that are so easy in JS (like cycling through objects, etc).

I have variables of custom types:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var questionConfiguration: QuestionConfiguration
var priorityConfiguration: PriorityConfiguration

Each of these types has an attribute, displayOrder, I want to access this dynamically. I have tried various things, including the following (i is a variable of type Int):

var configs = [self.questionConfiguration, self.priorityConfiguration]
print([configs[i]].displayOrder)
var configs = ["questionConfiguration", "priorityConfiguration"]
print([configs[i]].displayOrder)

How can I achieve this?

EDIT:

struct QuestionConfiguration: Codable {
    var displayOrder: Int
}

struct PriorityConfiguration: Codable {
    var displayOrder: Int
}

>Solution :

You can create a protocol for same property name then you can access it easily

protocol SameProp {
    var displayOrder: Int {get set}
}

class QuestionConfiguration : SameProp {
     var displayOrder : Int = 4
}

class PriorityConfiguration : SameProp {
     var displayOrder : Int = 6
 }

var questionConfiguration: QuestionConfiguration = QuestionConfiguration()
var priorityConfiguration: PriorityConfiguration = PriorityConfiguration()

var configs = [questionConfiguration, priorityConfiguration] as [SameProp]
for elements in configs{
    print(elements.displayOrder) // will print 4 and 6
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading