Created
September 27, 2017 07:18
-
-
Save omochi/b40e344ebad0b34a87b6792b5b772d01 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 LazyQueryArray<T> { | |
var cond: ((T) -> Bool)? | |
var _update: ((inout T) -> Void)? | |
var base: Array<T> | |
func resolve() -> Array<T> { | |
return base.map { x in | |
var x = x | |
if cond?(x) ?? true { | |
_update?(&x) | |
} | |
return x | |
} | |
} | |
mutating func update(_ f: @escaping (inout T) -> Void) { | |
_update = f | |
} | |
} | |
extension Array { | |
subscript(`where` wh: @escaping (Element) -> Bool) -> LazyQueryArray<Element> { | |
get { | |
return LazyQueryArray(cond: wh, _update: nil, base: self) | |
} | |
set { | |
self = newValue.resolve() | |
} | |
} | |
} | |
var s = [0, 1, 2, 3, 4] | |
print(s) | |
s[`where`: { $0 % 2 == 0 }].update { (x: inout Int) -> Void in x += 100 } | |
print(s) | |
/* | |
[0, 1, 2, 3, 4] | |
[100, 1, 102, 3, 104] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment