Created
March 15, 2024 15:37
-
-
Save bocato/3cab9016e1b9b145ef30e0be788b6029 to your computer and use it in GitHub Desktop.
DictionaryRepresentable.swift
This file contains 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 Foundation | |
#if DEBUG | |
/// Describes a objects as a dictionary. | |
/// - Used for debugging or testing purpuses. | |
public protocol DictionaryRepresentable {} | |
public extension DictionaryRepresentable { | |
func asDictionary() -> [String: Any] { | |
var dictionary: [String: Any] = .init() | |
let mirror = Mirror(reflecting: self) | |
for child in mirror.children { | |
if let label = child.label { | |
if let nsObject = child.value as? NSObject { | |
dictionary[label] = nsObject.asDictionary() | |
} else { | |
dictionary[label] = child.value | |
} | |
} | |
} | |
return dictionary | |
} | |
} | |
fileprivate extension NSObject { | |
func asDictionary() -> [String: Any] { | |
var dictionary: [String: Any] = .init() | |
var count: UInt32 = 0 | |
if let properties = class_copyPropertyList(type(of: self), &count) { | |
for i in 0..<Int(count) { | |
let property = properties[i] | |
let name = String(cString: property_getName(property)) | |
if let value = value(forKey: name) { | |
dictionary[name] = value | |
} | |
} | |
free(properties) | |
} | |
return dictionary | |
} | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment