Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Swift convert a class / struct data into dictionary?

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.

like image 303
Chen Li Yong Avatar asked Oct 06 '17 02:10

Chen Li Yong


People also ask

Is it possible to use a custom struct as a dictionary key Swift?

Any type that conforms to the Hashable protocol can be used as a dictionary's Key type, including all of Swift's basic types. You can use your own custom types as dictionary keys by making them conform to the Hashable protocol.

What is a struct in Swift?

In Swift, a struct is used to store variables of different data types. For example, Suppose we want to store the name and age of a person. We can create two variables: name and age and store value. However, suppose we want to store the same information of multiple people.

Why is dictionary unordered in Swift?

Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations. Arrays, sets, and dictionaries in Swift are always clear about the types of values and keys that they can store. This means that you can't insert a value of the wrong type into a collection by mistake.


1 Answers

You can just add a computed property to your struct to return a Dictionary with your values. Note that Swift native dictionary type doesn't have any method called value(forKey:). You would need to cast your Dictionary to NSDictionary:

struct Test {     let name: String     let age: Int     let height: Double     var dictionary: [String: Any] {         return ["name": name,                 "age": age,                 "height": height]     }     var nsDictionary: NSDictionary {         return dictionary as NSDictionary     } } 

You can also extend Encodable protocol as suggested at the linked answer posted by @ColGraff to make it universal to all Encodable structs:

struct JSON {     static let encoder = JSONEncoder() } extension Encodable {     subscript(key: String) -> Any? {         return dictionary[key]     }     var dictionary: [String: Any] {         return (try? JSONSerialization.jsonObject(with: JSON.encoder.encode(self))) as? [String: Any] ?? [:]     } } 

struct Test: Codable {     let name: String     let age: Int     let height: Double }  let test = Test(name: "Alex", age: 30, height: 170) test["name"]    // Alex test["age"]     // 30 test["height"]  // 170 
like image 106
Leo Dabus Avatar answered Sep 25 '22 00:09

Leo Dabus