Skip to content

Instantly share code, notes, and snippets.

@richy486
Created January 5, 2016 22:15
Show Gist options
  • Save richy486/00d1990b5446856c2c25 to your computer and use it in GitHub Desktop.
Save richy486/00d1990b5446856c2c25 to your computer and use it in GitHub Desktop.
Testing removing from pool in swift using Then
// Pool tests
// @richy486
// using Then
// https://github.com/devxoul/Then
public protocol Then {}
extension Then {
/// Makes it available to set properties with closures just after initializing.
///
/// let label = UILabel().then {
/// $0.textAlignment = .Center
/// $0.textColor = UIColor.blackColor()
/// $0.text = "Hello, World!"
/// }
public func then(@noescape block: Self -> Void) -> Self {
block(self)
return self
}
}
extension NSObject: Then {}
extension Item: Then {}
// -------- Pool Tests ---------
struct Item {
var active = true
}
var arr = [Item(active: false),Item(active: false),Item(active: false)]
let poolSize = 20
func getFromPool() -> Item {
if arr.count >= poolSize {
let filtered = arr.filter { $0.active == true }
if filtered.count > 0 {
return filtered[0]
}
}
let newItem = Item(active: true)
arr.append(newItem)
return newItem
}
func getFromPool2() -> Item {
guard let filtered = (arr.filter { $0.active }).first where arr.count >= poolSize else {
let newItem = Item(active: true)
arr.append(newItem)
return newItem
}
return filtered
}
func getFromPool3() -> Item {
guard let filtered = (arr.filter { $0.active }).first where arr.count >= poolSize else {
return Item(active: true).then{ arr.append($0) }
}
return filtered
}
func getFromPool4() -> Item {
return (arr.filter { $0.active }).first ?? Item(active: true).then{ arr.append($0) }
}
// Old way
func getFromPoolNil() -> Item? {
var item: Item?
if arr.count >= poolSize {
let filtered = arr.filter { $0.active == true }
if filtered.count > 0 {
item = filtered[0]
}
}
if item == nil {
item = Item(active: true)
arr.append(item!)
}
return item
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment