Skip to content

Instantly share code, notes, and snippets.

@richy486
Created February 8, 2016 22:37
Show Gist options
  • Save richy486/1f524d4100257fc270a6 to your computer and use it in GitHub Desktop.
Save richy486/1f524d4100257fc270a6 to your computer and use it in GitHub Desktop.
Object pool in swift
//
// Pool.swift
// @richy486
//
// Created by Richard Adem on 8/02/2016.
// Copyright © 2016 Richard Adem. All rights reserved.
//
import Foundation
class Pool<T: Hashable> {
var unusedPool = Array<T>()
var usingPool = Array<T>()
var factoryFunction: () -> T
required init(factoryFunction: () -> T) {
self.factoryFunction = factoryFunction;
}
func getItem() -> T {
var item: T
if unusedPool.count > 0 {
item = unusedPool.removeAtIndex(0)
} else {
item = factoryFunction()
}
usingPool.append(item)
return item
}
func returnItem(item: T) {
usingPool.removeObject(item)
unusedPool.append(item)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment