Instantly share code, notes, and snippets.

View firstLiteralMatch.swift
extension Collection where Element: Hashable {
/// Returns the first matching element in `needles`, along with its index.
func firstLiteralMatch<C: Collection>(from needles: C) -> (C.Element, Index)?
where C.Element: Collection, C.Element.Element == Element
{
let prefixes = Dictionary(grouping: needles, by: { $0.first! })
for i in indices {
if let possibleMatches = prefixes[self[i]] {
if let match = possibleMatches.first(where: { self[i...].starts(with: $0) }) {
return (match, i)
View munge.swift
// These functions turn nested tuples into flat ones
func munge<T, U, V>(_ x: ((T, U), V)) -> (T, U, V) {
return (x.0.0, x.0.1, x.1)
}
func munge<T, U, V>(_ x: (T, (U, V))) -> (T, U, V) {
return (x.0, x.1.0, x.1.1)
}
View CaseMap.swift
/// A dictionary wrapper that uses a `CaseIterable` type as its key.
/// This differs from a dictionary in two ways:
///
/// - Key-value pairs are accessed in a fixed order, which is the same
/// as the `Key`'s `allCases` property.
/// - Every possible key must have a value given, so using the key-based
/// subscript returns a non-optional value.
struct CaseMap<Key: CaseIterable & Hashable, Value> : Collection {
typealias Index = Key.AllCases.Index
View mapExceptLast.swift
let xs = [0,1,2,3,4,5]
let double: (Int) -> Int = { $0 * 2 }
let isEven: (Int) -> Bool = { $0 % 2 == 0 }
// Goal: [0,2,4,6,4,10]. Double all but the last even element.
extension Collection {
func mapExceptLast(matching predicate: (Element) -> Bool, transform: (Element) -> Element) -> [Element] {
var result: [Element] = []
View comparable-keypaths.swift
/// Returns a binary predicate using the given key path to create an ascending order
/// for elements of type `Root`.
func ascending<Root, Value: Comparable>(_ path: KeyPath<Root, Value>) -> (Root, Root) -> Bool {
return { $0[keyPath: path] < $1[keyPath: path] }
}
/// Returns a binary predicate using the given key path to create a descending order
/// for elements of type `Root`.
func descending<Root, Value: Comparable>(_ path: KeyPath<Root, Value>) -> (Root, Root) -> Bool {
return { $0[keyPath: path] > $1[keyPath: path] }
View interspersed.swift
extension Sequence {
func interspersed(with element: Element) -> [Element] {
var result: [Element] = []
var iterator = makeIterator()
if let first = iterator.next() {
result.append(first)
}
while let elementFromSelf = iterator.next() {
result.append(element)
result.append(elementFromSelf)
View dropFirstLast.swift
extension BidirectionalCollection {
func drop(first: Int, last: Int) -> SubSequence {
return self.dropFirst(first).dropLast(last)
}
}
let numbers = 0..<10
numbers.drop(first: 1, last: 1) // 1..<9
numbers.drop(first: 2, last: 4) // 2..<6
View choose.swift
extension Collection {
/// Chooses at random the given number of elements, using reservoir sampling
/// aka Algorithm R.
///
/// - Complexity: O(*n*) where *n* is the collection's count.
func choose<T>(upTo max: Int, using generator: T) -> [Element]
where T: RandomNumberGenerator
{
var i = index(startIndex, offsetBy: max, limitedBy: endIndex) ?? endIndex
var result = self[..<i].shuffled(using: generator)
View OptionSet+Collection.swift
/// This is a useful index that can store a comparable element or the end of
/// a collection. Similar to https://github.com/apple/swift/pull/15193
enum IndexWithEnd<T : Comparable> : Comparable {
case element(T)
case end
static func < (lhs: IndexWithEnd, rhs: IndexWithEnd) -> Bool {
switch (lhs, rhs) {
case (.element(let l), .element(let r)):
return l < r
View last.swift
extension Sequence {
func last(where predicate: (Element) throws -> Bool) rethrows -> Element? {
var result: Element? = nil
for el in self {
if try predicate(el) {
result = el
}
}
return result
}