Skip to content

Instantly share code, notes, and snippets.

@hisoka0917
Last active December 23, 2022 03:54
Show Gist options
  • Save hisoka0917/efcfbe006db929abecbe37376cf9e56b to your computer and use it in GitHub Desktop.
Save hisoka0917/efcfbe006db929abecbe37376cf9e56b to your computer and use it in GitHub Desktop.
Convert codable struct to dictionary
public protocol RawEnum {
var anyRawValue: Any { get }
}
public extension RawEnum where Self: RawRepresentable {
public var anyRawValue: Any {
get {
let mirror = Mirror(reflecting: self)
if mirror.displayStyle != .enum {
print("WARNING: You can only extend an enum with the Enum protocol")
}
return rawValue as Any
}
}
}
func convert2Dictionary<T>(_ any: T) -> Any {
let mirror = Mirror(reflecting: any)
if let style = mirror.displayStyle {
if style == .collection {
var array: [Any] = []
for (_, valueMaybe) in mirror.children {
let value = unwrap(valueMaybe)
array.append(convert2Dictionary(value))
}
return array
} else if style == .enum {
return (any as? RawEnum)?.anyRawValue ?? ""
} else {
var dict: [String: Any] = [:]
for (labelMaybe, valueMaybe) in mirror.children {
guard let label = labelMaybe else { continue }
let value = unwrap(valueMaybe)
dict[label] = convert2Dictionary(value)
}
return dict
}
} else {
return any
}
}
func unwrap<T>(_ any: T) -> Any
{
let mirror = Mirror(reflecting: any)
guard mirror.displayStyle == .optional, let first = mirror.children.first else {
return any
}
return first.value
}
@hisoka0917
Copy link
Author

Update for enum rawValue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment