Created
February 8, 2016 22:37
-
-
Save richy486/1f524d4100257fc270a6 to your computer and use it in GitHub Desktop.
Object pool 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
// | |
// 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