Skip to content

Instantly share code, notes, and snippets.

@RoyalIcing
Last active February 1, 2019 16:54
Show Gist options
  • Save RoyalIcing/b89800081ce28db4be04 to your computer and use it in GitHub Desktop.
Save RoyalIcing/b89800081ce28db4be04 to your computer and use it in GitHub Desktop.
Swift compact() for SequenceType
//: Playground - noun: a place where people can play
import Foundation
protocol OptionalParasite {
typealias WrappedParasite
func toArray() -> [WrappedParasite]
}
extension Optional: OptionalParasite {
typealias WrappedParasite = Wrapped
func toArray() -> [WrappedParasite] {
return flatMap { [$0] } ?? []
}
}
extension ImplicitlyUnwrappedOptional: OptionalParasite {
typealias WrappedParasite = Wrapped
func toArray() -> [WrappedParasite] {
return flatMap { [$0] } ?? []
}
}
extension SequenceType where Generator.Element: OptionalParasite {
func compact() -> [Generator.Element.WrappedParasite] {
return flatMap { element in
return element.toArray()
}
}
}
let abc: [Int?] = [
54,
46,
nil,
22,
1,
nil
]
abc.compact()
// [54, 46, 22, 1]
@thijsnado
Copy link

Here is a version that works with swift 4.2:

protocol OptionalParasite {
  associatedtype WrappedParasite

  func toArray() -> [WrappedParasite]
}

extension Optional: OptionalParasite {
  typealias WrappedParasite = Wrapped

  func toArray() -> [WrappedParasite] {
    return flatMap { [$0] } ?? []
  }
}

extension Sequence where Iterator.Element: OptionalParasite {
  func compact() -> [Iterator.Element.WrappedParasite] {
    return flatMap { element in
      return element.toArray()
    }
  }
}

let abc: [Int?] = [
  54,
  46,
  nil,
  22,
  1,
  nil
]

let foo = abc.compact()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment