Skip to content

Instantly share code, notes, and snippets.

struct OrderedSet<Element: Comparable & Hashable> {
private let elements: [Element]
init<S: Sequence>(_ elements: S) where S.Element == Element {
let set = Set<Element>(elements)
let array = Array(set)
self.elements = array.sorted()
}
}
struct AnyEquatable: Equatable {
static func ==(lhs: AnyEquatable, rhs: AnyEquatable) -> Bool {
return lhs.isEqual(rhs.value)
}
private let isEqual: (Any) -> Bool
private let value: Any
init<T: Equatable>(_ value: T) {
self.value = value
extension Collection {
subscript<T>(_ keyPath: KeyPath<Element, T>) -> [T] {
return map { $0[keyPath: keyPath] }
}
}
extension RangeReplaceableCollection {
subscript<U, T>(_ keyPath: KeyPath<Element, T>) -> U where U: RangeReplaceableCollection, U.Element == T {
return U(map { $0[keyPath: keyPath] })
}
extension Sequence {
func sorted<T: Comparable>(by keyPath: KeyPath<Element, T>, comparator: (T, T) -> Bool = { $0 < $1 }) -> [Element] {
return sorted(by: { (e1, e2) -> Bool in
return comparator(e1[keyPath: keyPath], e2[keyPath: keyPath])
})
}
}
let names = ["Alice", "Bob", "Charlie", "Dave"]
assert(names.sorted(by: \.count) == ["Bob", "Dave", "Alice", "Charlie"])
protocol Coalescable {
/// - Returns: One of the four cases:
/// - a new, combined instance
/// - nil, signalling the two cannot be combined
/// - `self`
/// - `other`
func coalesce(with other: Self) -> Self?
}
extension Sequence where Element: Coalescable {
// One note before we start: if the inhabitants of Value are a closed set,
// then making Value an enum is going to be a clearer model than using a
// protocol like this. I'm assuming you need to be able to retroactively add
// new members of Value.
// Can't use Equatable directly because of its Self requirement.
protocol HeteroEquatable {
func isEqualTo(_ value: HeteroEquatable) -> Bool
}
struct NearestKeyDictionary<Key: Comparable & Hashable, Value: Equatable>: ExpressibleByDictionaryLiteral {
// MARK: Type aliases
typealias Values = Dictionary<Key, Value>.Values
// MARK: Public properties
var allValues: Values {
return dictionary.values
}
@jakebromberg
jakebromberg / Array+EachCons.swift
Last active May 31, 2022 17:30 — forked from khanlou/Array+EachCons.swift
each_cons from Ruby in Swift as a function on Sequence
extension Collection {
func eachConsecutive(_ size: Int) -> Array<SubSequence> {
let droppedIndices = indices.dropFirst(size - 1)
return zip(indices, droppedIndices)
.map { return self[$0...$1] }
}
}
@jakebromberg
jakebromberg / SingleThreadedOperationQueue.swift
Last active May 2, 2018 22:57
Operation and dispatch queues on their own don't guarantee any single thread of execution. Here's one way to fix that.
import Foundation
@objc public final class SingleThreadedOperationQueue: Thread {
public typealias Operation = () -> ()
public func addOperation(_ operation: @escaping Operation) {
enqueueLock.lock()
defer {
enqueueLock.unlock()
}
final class ExecuteOnce {
typealias Work = () -> ()
private var work: Work?
init(_ work: @escaping Work) {
self.work = work
}
func execute() {
work?()