Skip to content

Instantly share code, notes, and snippets.

@siejkowski
Last active March 14, 2019 10:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save siejkowski/a2b187800f2e28b53c96 to your computer and use it in GitHub Desktop.
Save siejkowski/a2b187800f2e28b53c96 to your computer and use it in GitHub Desktop.
// 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]
@Marf1nN
Copy link

Marf1nN commented Mar 23, 2017

nice man

@jandamm
Copy link

jandamm commented Jul 14, 2017

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 } 
    }
}

@seriyvolk83
Copy link

seriyvolk83 commented Mar 14, 2019

extension LazySequenceProtocol where Self.Iterator.Element : Optionable {
    func flatten() -> [Self.Iterator.Element.Wrapped] {
        return compactMap { $0.value }
    }
}

@seriyvolk83
Copy link

// 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