Last active
March 14, 2019 10:20
-
-
Save siejkowski/a2b187800f2e28b53c96 to your computer and use it in GitHub Desktop.
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
// Optionable protocol exposes the subset of functionality required for flatten definition | |
protocol Optionable { | |
typealias Wrapped | |
var value: Wrapped? { get } | |
} | |
// extension for Optional provides the implementations for Optional enum | |
extension Optional : Optionable { | |
var value: Wrapped? { get { return self } } | |
} | |
extension SequenceType where Self.Generator.Element : Optionable { | |
func flatten() -> [Self.Generator.Element.Wrapped] { | |
return self.filter({ $0.value != nil }).map({ $0.value! }) | |
} | |
} | |
let sequence = [Optional.Some(1), Optional.Some(2), Optional.None, Optional.Some(3), Optional.Some(4)] | |
let flat = sequence.flatten() | |
flat // [1, 2, 3, 4] |
Updated Syntax:
protocol Optionable {
associatedtype Wrapped
var value: Wrapped? { get }
}
// extension for Optional provides the implementations for Optional enum
extension Optional : Optionable {
var value: Wrapped? { return self }
}
extension SequenceType where Self.Generator.Element : Optionable {
func flatten() -> [Self.Generator.Element.Wrapped] {
return flatMap { $0.value }
}
}
extension LazySequenceProtocol where Self.Iterator.Element : Optionable {
func flatten() -> [Self.Iterator.Element.Wrapped] {
return compactMap { $0.value }
}
}
// MARK: - Helpful methods for flattening dictionary
// Created by Alexander Volkov on 3/14/19.
// Copyright (c) 2019 Alexander Volkov. All rights reserved.
extension Dictionary where Value: Optionable {
/// flatten dictionary
public func flatten() -> [Key: Value.Wrapped] {
return self.filter({ (k, v) in
return v.value != nil
}).mapValues({$0.value!})
}
}
For example:
var userId: String? = ..
var query: String? = ..
let parameters: [String: Any?] = [
"query": query,
"userId": userId
]
parameters.flatten() // [String: Any]
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice man