Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
In-place editing of associated values in enums
struct MyArray<Element> : CustomStringConvertible {
class Storage<T> {
var values = ContiguousArray<T>()
}
var storage = Storage<Element>()
init<T: Sequence>(contentsOf s: T) where T.Element == Element {
for item in s { storage.values.append(item) }
}
mutating func append(_ value: Element) {
if isKnownUniquelyReferenced(&storage) {
print("KEEP STORAGE")
storage.values.append(value)
}
else {
print("COPY STORAGE")
let old = storage.values
storage = Storage<Element>()
storage.values.append(contentsOf: old)
}
}
var description : String { return storage.values.description }
}
enum Values {
case release
case string(String)
case array ([String])
case myarray (MyArray<String>)
}
extension Values {
mutating func add(_ item: String) -> Bool {
guard case .array(var array) = self else { return false }
self = .release
array.append(item) // this only changes the copy of course
self = .array(array)
return true
}
mutating func madd(_ item: String) -> Bool {
guard case .myarray(var array) = self else { return false }
self = .release // make sure the RC of `array` drops to 1
array.append(item)
self = .myarray(array)
return true
}
}
var values = [ Values ]()
values.append(.array(["hallo"]))
_ = values[0].add("World")
print(values[0])
values.append(.myarray(MyArray(contentsOf: ["hallo"])))
_ = values[1].madd("World")
print(values[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment