Skip to content

Instantly share code, notes, and snippets.

@bleeckerj
Forked from khanlou/Swift2.swift
Created July 22, 2017 00:15
Show Gist options
  • Select an option

  • Save bleeckerj/fcb008f80b82f81236aa930f12619da9 to your computer and use it in GitHub Desktop.

Select an option

Save bleeckerj/fcb008f80b82f81236aa930f12619da9 to your computer and use it in GitHub Desktop.
`any`, `all`, `none`, `first`, and `count` on SequenceType in Swift
extension Sequence {
func any(_ predicate: (Self.Iterator.Element) throws -> Bool) rethrows -> Bool {
for element in self {
let result = try predicate(element)
if result {
return true
}
}
return false
}
func all(_ predicate: (Self.Iterator.Element) throws -> Bool) rethrows -> Bool {
for element in self {
let result = try predicate(element)
if !result {
return false
}
}
return true
}
func none(_ predicate: (Self.Iterator.Element) throws -> Bool) rethrows -> Bool {
let result = try self.any(predicate: predicate)
return !result
}
func count(_ predicate: (Self.Iterator.Element) throws -> Bool) rethrows -> Int {
var count = 0
for element in self {
if try predicate(element) {
count += 1
}
}
return count
}
}
import Foundation
extension SequenceType {
@warn_unused_result
func any(@noescape predicate: (Self.Generator.Element) throws -> Bool) rethrows -> Bool {
for element in self {
let result = try predicate(element)
if result {
return true
}
}
return false
}
@warn_unused_result
func all(@noescape predicate: (Self.Generator.Element) throws -> Bool) rethrows -> Bool {
for element in self {
let result = try predicate(element)
if !result {
return false
}
}
return true
}
@warn_unused_result
func none(@noescape predicate: (Self.Generator.Element) throws -> Bool) rethrows -> Bool {
for element in self {
let result = try predicate(element)
if result {
return false
}
}
return true
}
//part of the standard library as of Swift 3, as `first(where:)`
@warn_unused_result
func first(@noescape predicate: (Self.Generator.Element) throws -> Bool) rethrows -> Self.Generator.Element? {
for element in self {
if try predicate(element) {
return element
}
}
return nil
}
@warn_unused_result
func count(@noescape predicate: (Self.Generator.Element) throws -> Bool) rethrows -> Int {
var count = 0
for element in self {
if try predicate(element) {
count += 1
}
}
return count
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment