Created
September 20, 2018 14:27
-
-
Save PaulTaykalo/0877d32dfcba2a2de15ddc06177c4a7f to your computer and use it in GitHub Desktop.
MinMax.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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