Created
September 17, 2015 04:50
-
-
Save danott/2f9f3b91238d99de986f to your computer and use it in GitHub Desktop.
Some generic, functional swift methods.
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
func any<S>(source: [S], predicate: (S) -> Bool) -> Bool { | |
for element in source { | |
if predicate(element) { return true } | |
} | |
return false | |
} | |
func any<S>(source: [S], predicate: (Int, S) -> Bool) -> Bool { | |
for (index, element) in enumerate(source) { | |
if predicate(index, element) { return true } | |
} | |
return false | |
} | |
func every<S>(source: [S], predicate: (S) -> Bool) -> Bool { | |
for element in source { | |
if !predicate(element) { return false } | |
} | |
return true | |
} | |
func every<S>(source: [S], predicate: (Int, S) -> Bool) -> Bool { | |
for (index, element) in enumerate(source) { | |
if !predicate(index, element) { return false } | |
} | |
return true | |
} | |
func none<S>(source: [S], predicate: (S) -> Bool) -> Bool { | |
return !any(source, predicate) | |
} | |
func none<S>(source: [S], predicate: (Int, S) -> Bool) -> Bool { | |
return !any(source, predicate) | |
} | |
func head<S>(source: [S]) -> S? { | |
return source.first | |
} | |
func tail<S>(source: [S]) -> [S] { | |
if source.count <= 1 { return [] } | |
return Array(source[1..<source.count]) | |
} | |
extension Array { | |
func any(predicate: (T) -> Bool) -> Bool { | |
for element in self { | |
if predicate(element) { return true } | |
} | |
return false | |
} | |
func any(predicate: (Int, T) -> Bool) -> Bool { | |
for (index, element) in enumerate(self) { | |
if predicate(index, element) { return true } | |
} | |
return false | |
} | |
func every(predicate: (T) -> Bool) -> Bool { | |
for element in self { | |
if !predicate(element) { return false } | |
} | |
return true | |
} | |
func every(predicate: (Int, T) -> Bool) -> Bool { | |
for (index, element) in enumerate(self) { | |
if !predicate(index, element) { return false } | |
} | |
return true | |
} | |
func none(predicate: (T) -> Bool) -> Bool { | |
return !any(predicate) | |
} | |
func none(predicate: (Int, T) -> Bool) -> Bool { | |
return !any(predicate) | |
} | |
var head: T? { | |
return self.first | |
} | |
var tail: Array<T> { | |
if count <= 1 { return [] } | |
return Array(self[1..<count]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment