For example:
class Test {
var name: String;
var age: Int;
var height: Double;
func convertToDict() -> [String: AnyObject] { ..... }
}
let test = Test();
test.name = "Alex";
test.age = 30;
test.height = 170;
let dict = test.convertToDict();
dict will have content:
{"name": "Alex", "age": 30, height: 170}
Is this possible in Swift?
And can I access a class like a dictionary, for example probably using:
test.value(forKey: "name");
Or something like that?
Thanks.
You could use Reflection and Mirror like this to make it more dynamic and ensure you do not forget a property.
["name": "Ryan", "position": 2, "good": true, "car": "Ford"]
You can just add a computed property to your
struct
to return aDictionary
with your values. Note that Swift native dictionary type doesn't have any method calledvalue(forKey:)
. You would need to cast yourDictionary
toNSDictionary
:You can also extend
Encodable
protocol as suggested at the linked answer posted by @ColGraff to make it universal to allEncodable
structs: