Skip to content

Instantly share code, notes, and snippets.

@omochi
Created September 27, 2017 07:41
Show Gist options
  • Save omochi/76e781ebd927a0ed927f89fd94718d53 to your computer and use it in GitHub Desktop.
Save omochi/76e781ebd927a0ed927f89fd94718d53 to your computer and use it in GitHub Desktop.
struct SparseSlice<T> {
var data: Dictionary<Int, T>
mutating func update(_ f: (inout T) -> Void) {
for (k, v) in data {
var v = v
f(&v)
data[k] = v
}
}
}
extension Array {
subscript(`where` wh: @escaping (Element) -> Bool) -> SparseSlice<Element> {
get {
var data = [Int: Element]()
for i in startIndex..<endIndex {
if wh(self[i]) {
data[i] = self[i]
}
}
return SparseSlice(data: data)
}
set {
for (i, v) in newValue.data {
self[i] = v
}
}
}
}
var s = [0, 1, 2, 3, 4]
print(s)
s[where: { $0 % 2 == 0 }].update { (x: inout Int) in x += 100 }
print(s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment