Created
March 9, 2017 14:40
-
-
Save juzooda/d2942c8d7535b2365a75a2f2c779da15 to your computer and use it in GitHub Desktop.
Simple Protocol to convert swift structs to dictionaries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
struct Person: DictionaryConvertor { | |
let name: String | |
let job: [Job]? | |
let errors: [String]? | |
} | |
struct Job: DictionaryConvertor { | |
let title: String | |
let salary: Salary | |
let level: Int | |
} | |
struct Salary: DictionaryConvertor { | |
let amount: Int | |
let currency: String | |
} | |
protocol DictionaryConvertor { | |
func toDictionary() -> [String : Any] | |
} | |
extension DictionaryConvertor { | |
func toDictionary() -> [String : Any] { | |
let reflect = Mirror(reflecting: self) | |
let children = reflect.children | |
let dictionary = toAnyHashable(elements: children) | |
return dictionary | |
} | |
func toAnyHashable(elements: AnyCollection<Mirror.Child>) -> [String : Any] { | |
var dictionary: [String : Any] = [:] | |
for element in elements { | |
if let key = element.label { | |
if let collectionValidHashable = element.value as? [AnyHashable] { | |
dictionary[key] = collectionValidHashable | |
} | |
if let validHashable = element.value as? AnyHashable { | |
dictionary[key] = validHashable | |
} | |
if let convertor = element.value as? DictionaryConvertor { | |
dictionary[key] = convertor.toDictionary() | |
} | |
if let convertorList = element.value as? [DictionaryConvertor] { | |
dictionary[key] = convertorList.map({ e in | |
e.toDictionary() | |
}) | |
} | |
} | |
} | |
return dictionary | |
} | |
} | |
let salary = Salary(amount: 100, currency: "EURO") | |
let job = Job(title: "Dittybopper", salary: salary, level: 5) | |
let job2 = Job(title: "Substitute Teacher", salary: salary, level: 5) | |
let person = Person(name: "Juzo", job: [job, job2], errors: []).toDictionary() | |
print(person) | |
let responseData = try! JSONSerialization.data(withJSONObject: person, options: .prettyPrinted) | |
print(responseData) | |
Enums don't work for me is there a fix?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You are a Savior!