Skip to content

Instantly share code, notes, and snippets.

@griotspeak
Created June 1, 2015 16:10
Show Gist options
  • Save griotspeak/17d2f63780e9549a3335 to your computer and use it in GitHub Desktop.
Save griotspeak/17d2f63780e9549a3335 to your computer and use it in GitHub Desktop.
Swift.Set extensions
//
// Set.swift
// TonalKit
//
// Created by TJ Usiyan on 3/2/15.
// Copyright (c) 2015 buttons-and-lights. All rights reserved.
// https://gist.github.com/17d2f63780e9549a3335.git
import Foundation
extension Set {
func reduce<U>(initial: U, @noescape combine: (U, T) -> U) -> U {
return Swift.reduce(self, initial, combine)
}
func filter(includeElement: (T) -> Bool) -> Set {
return reduce(Set()) { includeElement($1) ? $0.union($1) : $0 }
}
func map<U>(transform: (T) -> U) -> Set<U> {
return reduce(Set<U>()) { $0.union(transform($1)) }
}
}
extension Set {
func union(items: T ...) -> Set {
return union(items)
}
}
extension Set {
func mapSome<U>(transform: (T) -> U?) -> Set<U> {
var result = Set<U>()
for x in self {
if let y = transform(x) {
result.unionInPlace([y]) /* @todo rdar inability to append 2015-03-15 */
}
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment