Created
September 27, 2017 07:41
-
-
Save omochi/76e781ebd927a0ed927f89fd94718d53 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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