Skip to content

Instantly share code, notes, and snippets.

@nbasham
Last active February 18, 2017 00:59
Show Gist options
  • Save nbasham/a94419c691b9e9afa182f48a966dfdd9 to your computer and use it in GitHub Desktop.
Save nbasham/a94419c691b9e9afa182f48a966dfdd9 to your computer and use it in GitHub Desktop.
Swift extension of Array. Adds every function to test if all elements meet a criteria and filterReturnIndexes that filters and returns the indexes of elements that meet criteria.
import UIKit
public extension Sequence {
// return true if all elements return true
func every<T>(predicate:(T) -> Bool) -> Bool {
for item in self {
if !predicate(item as! T) {
return false
}
}
return true
}
}
public extension Array {
// return indexes of all elements that return true
func filterReturnIndexes(predicate:(Int) -> Bool) -> [Int] {
var result = [Int]()
for i in 0..<self.count {
if predicate(i) {
result.append(i)
}
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment