reza_khalafi
reza_khalafi

Reputation: 6534

How to set values in Struct object when does not know that type in iOS Swift 3.1?

I made Struct object like this:

struct Lamp {
    var name:String!
    var age:Int!
}

And i have info Dictionary like this:

let infoDict = [
            "name":"Jason",
            "age":23
            ] as [String : Any]  

And make new instance of Lamp struct object:

var lamp = Lamp()

And:

var labelsArr : Array<String>  = []
for property in Mirror(reflecting: lamp).children {
    print("label : \(String(describing:  property.label ))") //name , age
    labelsArr.append(property.label!)
}

So finally i want to set values of infoDict to lamp instance. consider i do not want to set it manually like this:

lamp.name = infoDict["name"]
lamp.age = infoDict["age"]

I want set these values dynamically. Because i do not know what properties have set in Lamp struct, the code must recognize what properties has been set in Lamp and set values by self.

Thank you.

Upvotes: 1

Views: 663

Answers (2)

mBrissman
mBrissman

Reputation: 136

You should checkout Unbox by John Sundell

It's a really nice JSON decoder written in Swift.

Upvotes: -1

Sweeper
Sweeper

Reputation: 270780

So I assume you don't know the type of lamp at compile time (so the compile time type is Any) and its type can only be in a finite set of types. And you want to initialise this lamp using JSON.

Now I am confused. Let's say you initialised lamp successfully, then what? Since you don't know what type it is, you can't really access any properties or methods.

Nevertheless, I thought of a solution. Make all the types that lamp can possibly be of conform to a protocol:

protocol JSONInitializable {
    func initialize(with json: [String: Any])
}

For example, the Lamp struct:

struct Lamp {
    ...

    func initialize(with json: [String: Any]) {
        name = json["name"] as! String
        age = json["age"] as! Int
    }
}

You do this for all other types.

When you want to initialise an unknown type lamp. You simply cast it to JSONInitializable:

if let jsonInitializable = lamp as? JSONInitializable {
    jsonInitializable.initialize(with: infoDict)
}

Upvotes: 2

Related Questions