Created
June 11, 2014 16:53
-
-
Save bnickel/e22a0e6b7f4c8acc022a to your computer and use it in GitHub Desktop.
Example filter implementation in Swift.
This file contains hidden or 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
import Foundation | |
struct FilteringGenerator<T where T:Generator> : Generator { | |
let test:(T.Element) -> Bool | |
var generator:T | |
init(_ generator:T, _ test: (T.Element) -> Bool) { | |
self.test = test | |
self.generator = generator | |
} | |
mutating func next() -> T.Element? { | |
var item = generator.next() | |
while item && !test(item!) { | |
item = generator.next() | |
} | |
return item | |
} | |
} | |
struct FilteringSequence<T where T:Sequence> : Sequence { | |
let sequence:T | |
let test:T.GeneratorType.Element -> Bool | |
init(_ sequence:T, _ test:T.GeneratorType.Element -> Bool) { | |
self.sequence = sequence | |
self.test = test | |
} | |
func generate() -> FilteringGenerator<T.GeneratorType> { | |
return FilteringGenerator(sequence.generate(), test) | |
} | |
} | |
func myFilter<S : Sequence>(source: S, includeElement: (S.GeneratorType.Element) -> Bool) -> FilteringSequence<S> { | |
return FilteringSequence(source, includeElement) | |
} |
This file contains hidden or 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
class MyFilterTests: XCTestCase { | |
func testBuiltIn() { | |
self.measureBlock() { | |
let x = filter(1..100000) { $0 % 5 == 0 } | |
println(reduce(x, 0) { $1 - $0 }) | |
} | |
} | |
func testCustom() { | |
self.measureBlock() { | |
let x = myFilter(1..100000) { $0 % 5 == 0 } | |
println(reduce(x, 0) { $1 - $0 }) | |
} | |
} | |
func testRaw() { | |
self.measureBlock() { | |
var acc = 0 | |
for i in 1..100000 { | |
if i % 5 == 0 { | |
acc = i - acc | |
} | |
} | |
println(acc) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment