From e2f13e166b73d06cdf938de786789e2e9a80fac5 Mon Sep 17 00:00:00 2001 From: ryohey Date: Sun, 9 Jun 2019 00:25:07 +0900 Subject: [PATCH] Add Dictionary.removeEmpty() --- .../ProjectSpec/CollectionExtensions.swift | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Sources/ProjectSpec/CollectionExtensions.swift 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) + } +}