Skip to content

Instantly share code, notes, and snippets.

@PaulTaykalo
Created September 20, 2018 14:27
Show Gist options
  • Save PaulTaykalo/0877d32dfcba2a2de15ddc06177c4a7f to your computer and use it in GitHub Desktop.
Save PaulTaykalo/0877d32dfcba2a2de15ddc06177c4a7f to your computer and use it in GitHub Desktop.
MinMax.swift
extension Sequence {
@warn_unqualified_access
public func min<T:Comparable>(by: (Element) throws -> T) rethrows -> Element? {
return try self.min { try by($0) < by($1) }
}
@warn_unqualified_access
public func max<T:Comparable>(by: (Element) throws -> T) rethrows -> Element? {
return try self.max { try by($0) > by($1) }
}
}
struct S {
let a: Int
let b: Int
}
let items:[S] = [S(a:1, b:2), S(a:2, b: 5)]
let minimum = items.min { $0.a + $0.b } // Bit shorter
let minimum2 = items.min { $0.a + $0.b < $1.a + $1.b}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment