Last active
December 23, 2022 03:54
-
-
Save hisoka0917/efcfbe006db929abecbe37376cf9e56b to your computer and use it in GitHub Desktop.
Convert codable struct to dictionary
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
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Update for enum rawValue