Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Simple naive implementation of custom Array-like structure
import Foundation
struct MyArray<Element> : CustomStringConvertible {
var description: String {
var mutableDescription = "["
for i in 0..<count {
mutableDescription += "\"\(elementAtIndex(i)) "
if i != count - 1 {
mutableDescription += ", "
}
}
mutableDescription += "]"
return mutableDescription
}
private let dataRepresentation: NSMutableData
init() {
dataRepresentation = NSMutableData()
}
init(elements: Element ...) {
self.init(elements: elements)
}
init(elements: [Element]) {
self.init()
for element in elements {
append(element)
}
}
private let elementSize = sizeof(Element)
var count: Int { return dataRepresentation.length / elementSize }
subscript(index: Int) -> Element {
get {
return elementAtIndex(index)
}
set {
insert(newValue, toIndex: index)
}
}
func elementAtIndex(index: Int) -> Element {
let subdata = dataRepresentation.subdataWithRange(NSRange(location: index * elementSize, length: elementSize))
return UnsafeMutablePointer<Element>(subdata.bytes).memory
}
mutating func append(element: Element) {
var copyElement = element
dataRepresentation.appendBytes(&copyElement, length: elementSize)
}
mutating func insert(element: Element, toIndex index: Int) {
var newElement = element
dataRepresentation.replaceBytesInRange(NSRange(location: index * elementSize, length: 0), withBytes: NSData(bytes: &newElement, length: elementSize).bytes, length: elementSize)
}
mutating func removeElementAtIndex(index: Int) {
CFDataDeleteBytes(dataRepresentation, CFRangeMake(index * elementSize, elementSize))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment