Slide 4
Slide 4 text
Sample
public struct Bag0 {
public struct Key: Equatable {
fileprivate let value: UInt64
fileprivate init(value: UInt64) {
self.value = value
}
public static func == (lhs: Key, rhs: Key) -> Bool {
return lhs.value == rhs.value
}
}
private var buffer = [(key: Key, element: Element)]()
private var nextKey = Key(value: 0)
public init() {}
@discardableResult
public mutating func add(_ element: Element) -> Key {
let key = nextKey
nextKey = Key(value: key.value &+ 1)
buffer.append((key: key, element: element))
return key
}
@discardableResult
public mutating func remove(for key: Key) -> Element? {
if let index = buffer.indices.reversed().first(where: { buffer[$0].key == key }) {
return buffer.remove(at: index).element
}
return nil
}
}