Last active
November 20, 2020 23:52
-
-
Save MarcoEidinger/8679ccc283835255a82c7a2110da2974 to your computer and use it in GitHub Desktop.
Variadic parameters are converted to an array while inside a function. Forwarding this array to another function which accepts variadic parameters will result in a nested array. Use this function to remove nesting arrays and remove nil values
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
extension Array where Element == Any { | |
/** | |
Variadic parameters are converted to an array while inside a function. Forwarding this array to another function which accepts variadic parameters will result in a nested array | |
Use this function to remove nesting arrays and remove nil values | |
``` | |
var anyArray: [Any] = [[["Hello", nil]] | |
var result = anyArray.flatCompactMapForVariadicParameters() // result is ["Hello"] | |
``` | |
*/ | |
func flatCompactMapForVariadicParameters() -> [Any] { | |
var filtered: [Any] = [] | |
for el in self { | |
if let array = el as? [Any] { | |
return array.flatCompactMapForVariadicParameters() | |
} | |
} | |
for case let optionalAny in self { | |
if Optional.isNil(optionalAny) == false { | |
filtered.append(optionalAny) | |
} | |
} | |
return filtered | |
} | |
} | |
extension Optional { | |
static func isNil(_ object: Wrapped) -> Bool { | |
switch object as Any { | |
// swiftformat:disable:next typeSugar | |
case Optional<Any>.none: | |
return true | |
default: | |
return false | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment