diff --git a/Sources/ProjectSpec/CollectionExtensions.swift b/Sources/ProjectSpec/CollectionExtensions.swift new file mode 100644 index 00000000..40803a24 --- /dev/null +++ b/Sources/ProjectSpec/CollectionExtensions.swift @@ -0,0 +1,33 @@ +import Foundation + +private protocol EmptyRemovable { + func removeEmpty() -> Self + var isEmpty: Bool { get } +} + +extension Array: EmptyRemovable { + public func removeEmpty() -> Array { + return compactMap { + if let e = ($0 as? EmptyRemovable)?.removeEmpty() { + return e.isEmpty ? nil : e as? Element + } + return $0 + } + } +} + +extension Dictionary: EmptyRemovable { + // this is a little trick that defines the generics parameter from optional Value to unwrapped Value + private static func removeEmpty(dict: Dictionary) -> Dictionary { + return dict.compactMapValues { + if let e = ($0 as? EmptyRemovable)?.removeEmpty() { + return e.isEmpty ? nil : e as? Value + } + return $0 + } + } + + public func removeEmpty() -> Dictionary { + return Dictionary.removeEmpty(dict: self) + } +}