Skip to content

Instantly share code, notes, and snippets.

@vlaminck
Created July 7, 2016 19:51
Show Gist options
  • Save vlaminck/486ae1c3d0d8ba93b77bad41ed238435 to your computer and use it in GitHub Desktop.
Save vlaminck/486ae1c3d0d8ba93b77bad41ed238435 to your computer and use it in GitHub Desktop.
A playground that tests variations of a CollectionType extension for finding elements by type
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
class Base {
var number: Int?
}
class Sub: Base {}
class Other: Base {}
let s = Sub()
let o = Other()
var a: [Base] = [s, o]
let f = a.filter { return $0 is Sub }.first
f
func findIt<U>(type: U.Type, within: [Base]) -> U? {
return within.filter { return $0 is U }.first as? U
}
findIt(Sub.self, within: a)
findIt(Other.self, within: a)
extension CollectionType {
func firstOfTypeByFilter<U>(c: U.Type) -> U? {
return self.filter { return $0 is U }.first as? U
}
func firstOfTypeByFlatMap<U>(c: U.Type) -> U? {
return self.lazy.flatMap { return $0 as? U }.first
}
func firstOfTypeByFor<U>(c: U.Type) -> U? {
for item in self {
if item is U {
return item as? U
}
}
return nil
}
func firstOfType<U>(c: U.Type) -> U? {
for item in self where item is U {
return item as? U
}
return nil
}
}
a.firstOfType(Sub)
a.firstOfType(Other)
a.firstOfType(Base)
a.firstOfType(String)
a.firstOfType(s.dynamicType)
let index = a.indexOf { $0 is Other }
index
func test<U>(data: U) {
if let index = a.indexOf({ $0 is U }) {
_ = a.removeAtIndex(index)
}
}
a
test(o)
a.forEach {
print($0.dynamicType)
}
var testArray: [Base] = (0...1000).map {
if $0 % 2 == 0 {
let item = Sub()
item.number = $0
return item
} else {
let item = Other()
item.number = $0
return item
}
}
func time(closure: () -> Void) -> NSTimeInterval {
let runs = 100
var allRuns: [NSTimeInterval] = []
(0...runs).forEach { _ in
let start = NSDate()
closure()
let end = start.timeIntervalSinceNow
allRuns.append(abs(end))
}
let total = allRuns.reduce(0, combine: +)
return total / NSTimeInterval(runs)
}
time {
testArray.firstOfTypeByFilter(Sub)
}
time {
testArray.firstOfTypeByFlatMap(Sub)
}
time {
testArray.firstOfTypeByFor(Sub)
}
time {
testArray.firstOfType(Sub)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment