mirror of
https://github.com/samsonjs/SwiftBatteries.git
synced 2026-04-27 15:07:46 +00:00
tweak CollectionType extensions
This commit is contained in:
parent
4b598541c0
commit
44dfb748ee
1 changed files with 8 additions and 6 deletions
|
|
@ -8,11 +8,13 @@ import Foundation
|
||||||
|
|
||||||
public extension CollectionType {
|
public extension CollectionType {
|
||||||
|
|
||||||
|
typealias T = Generator.Element
|
||||||
|
|
||||||
/// Returns elements of the collection that match the given regular expression.
|
/// Returns elements of the collection that match the given regular expression.
|
||||||
/// If elements are String or NSString instances they will be matched directly.
|
/// If elements are String or NSString instances they will be matched directly.
|
||||||
/// if they are NSObject instances their -description is matched. Otherwise
|
/// if they are NSObject instances their -description is matched. Otherwise
|
||||||
/// they are not matched.
|
/// they are not matched.
|
||||||
func grep(regex: String) throws -> [Self.Generator.Element] {
|
func grep(regex: String) throws -> [T] {
|
||||||
let re = try NSRegularExpression(pattern: regex, options: NSRegularExpressionOptions(rawValue: 0))
|
let re = try NSRegularExpression(pattern: regex, options: NSRegularExpressionOptions(rawValue: 0))
|
||||||
return filter({ item -> Bool in
|
return filter({ item -> Bool in
|
||||||
if let string = item as? String {
|
if let string = item as? String {
|
||||||
|
|
@ -40,11 +42,11 @@ func randomInt(max: Int) -> Int {
|
||||||
return 1 + Int(n)
|
return 1 + Int(n)
|
||||||
}
|
}
|
||||||
|
|
||||||
public extension CollectionType where Self.Index: Strideable {
|
public extension CollectionType where Index: RandomAccessIndexType {
|
||||||
|
|
||||||
/// Returns a random element, or nil if the collection is empty
|
/// Returns a random element, or nil if the collection is empty
|
||||||
func sample() -> Generator.Element? {
|
func sample() -> T? {
|
||||||
guard count > 0 else {
|
guard !isEmpty else {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
let max = Int(count.toIntMax())
|
let max = Int(count.toIntMax())
|
||||||
|
|
@ -58,8 +60,8 @@ public extension CollectionType where Self.Generator.Element: Equatable {
|
||||||
|
|
||||||
/// Returns the unique elements of a sorted collection by collapsing runs of
|
/// Returns the unique elements of a sorted collection by collapsing runs of
|
||||||
/// identical elements.
|
/// identical elements.
|
||||||
func unique() -> [Self.Generator.Element] {
|
func unique() -> [T] {
|
||||||
var last: Self.Generator.Element?
|
var last: T?
|
||||||
return filter({ item -> Bool in
|
return filter({ item -> Bool in
|
||||||
let isUnique: Bool = last == nil || last != item
|
let isUnique: Bool = last == nil || last != item
|
||||||
last = item
|
last = item
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue