Skip to content

Instantly share code, notes, and snippets.

@vialyx
Created October 17, 2018 18:58
Show Gist options
  • Save vialyx/06a91752a954212d48663abe8742d44d to your computer and use it in GitHub Desktop.
Save vialyx/06a91752a954212d48663abe8742d44d to your computer and use it in GitHub Desktop.
struct Buffer<Element> {
enum BufferError: Error {
case outOfBounds
}
private var items: [Element] = []
mutating func add(_ item: Element) {
items.append(item)
}
func get(index: Int) throws -> Element {
guard index < items.count else {
throw BufferError.outOfBounds
}
return items[index]
}
}
var stringBuffer = Buffer<String>()
stringBuffer.add("New String")
stringBuffer.add("ViVa")
(0...3).forEach {
do {
let itemFromBuffer = try stringBuffer.get(index: $0)
print("itemFromBuffer: '\(itemFromBuffer)' at index: \($0)")
} catch {
print("\(error) at index: \($0)")
}
}
/*
itemFromBuffer: 'New String' at index: 0
itemFromBuffer: 'ViVa' at index: 1
outOfBounds at index: 2
outOfBounds at index: 3
*/
var intBuffer = Buffer<Int>()
intBuffer.add(1)
intBuffer.add(100)
intBuffer.add(3000)
(0...3).forEach {
let intItem = try? intBuffer.get(index: $0)
print("intItem: '\(String(describing: intItem))' at index: \($0)")
}
/*
intItem: 'Optional(1)' at index: 0
intItem: 'Optional(100)' at index: 1
intItem: 'Optional(3000)' at index: 2
intItem: 'nil' at index: 3
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment