Skip to content

Instantly share code, notes, and snippets.

@juzooda
Created March 9, 2017 14:40
Show Gist options
  • Save juzooda/d2942c8d7535b2365a75a2f2c779da15 to your computer and use it in GitHub Desktop.
Save juzooda/d2942c8d7535b2365a75a2f2c779da15 to your computer and use it in GitHub Desktop.
Simple Protocol to convert swift structs to dictionaries
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)
@cpajuelodeveloper
Copy link

You are a Savior!

@paul-fessele
Copy link

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