Skip to content

Instantly share code, notes, and snippets.

@azone
Created April 8, 2020 09:47
Show Gist options
  • Save azone/a4252b1791b8381fa41e6aa43b8437d2 to your computer and use it in GitHub Desktop.
Save azone/a4252b1791b8381fa41e6aa43b8437d2 to your computer and use it in GitHub Desktop.
Useful swift extensions for `Sequence` and `Optional` with `Collection` wrapper
public extension Sequence {
func all(_ predicate: (Element) throws -> Bool) rethrows -> Bool {
try allSatisfy(predicate)
}
func any(_ predicate: (Element) throws -> Bool) rethrows -> Bool {
try contains(where: predicate)
}
}
public extension Sequence where Element: AdditiveArithmetic {
func sum() -> Element {
reduce(Element.zero, +)
}
}
public extension Optional where Wrapped: Collection {
var isEmpty: Bool {
guard case let .some(val) = self else {
return true
}
return val.isEmpty
}
}
@azone
Copy link
Author

azone commented Apr 8, 2020

Now you can use:

let a = [1, 2, 3, 4, 5]
a.sum() // 15
a.any { $0 >= 3 } // true
a.all { $0 >= 3 } // false

let s: String? = nil
s.isEmpty // true

let a2: [Int]? = nil
a2.isEmpty // true

let a3: [Int]? = [1, 2, 3]
a3.isEmpty // false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment