Created
April 30, 2015 11:42
-
-
Save kirsteins/1c6ab9e460f222fd1c21 to your computer and use it in GitHub Desktop.
Array extensions and helpers
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
internal extension Array { | |
internal func get(index: Int) -> Element? { | |
return index >= 0 && index < self.count ? self[index] : nil | |
} | |
internal func at(indexes: [Int]) -> [Element] { | |
var result: [Element] = [] | |
for index in indexes { | |
result.append(self[index]) | |
} | |
return result | |
} | |
internal func at(indexes: Int...) -> [Element] { | |
return self.at(indexes) | |
} | |
internal func every(test: (Element) -> Bool) -> Bool { | |
for element in self { | |
if test(element) == false { | |
return false | |
} | |
} | |
return true | |
} | |
internal func find(test: (Element) -> Bool) -> Element? { | |
for element in self { | |
if test(element) { | |
return element | |
} | |
} | |
return nil | |
} | |
internal func findIndex(test: (Element) -> Bool) -> Int? { | |
for (index, element) in enumerate(self) { | |
if test(element) { | |
return index | |
} | |
} | |
return nil | |
} | |
internal func findLastIndex(test: (Element) -> Bool) -> Int? { | |
let count = self.count | |
for (index, _) in enumerate(self) { | |
let reverseIndex = count - (index + 1) | |
let element : T = self[reverseIndex] | |
if test(element) { | |
return reverseIndex | |
} | |
} | |
return nil | |
} | |
} | |
public func compact<T>(array: [T?]) -> [T] { | |
return array.filter{$0 != nil}.map{$0!} | |
} | |
public func compact<T>(array: T?...) -> [T] { | |
return compact(array) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment