Last active
September 27, 2017 07:59
-
-
Save t-ae/4d4037e8cfddf7dc99de2f91412248af to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Kollection<T> { | |
var array: Array<T> | |
let indices: [Int] | |
subscript(indice: Int) -> T { | |
get { | |
precondition(indices.contains(indice)) | |
return array[indice] | |
} | |
set { | |
precondition(indices.contains(indice)) | |
array[indice] = newValue | |
} | |
} | |
subscript(indices indices: [Int]) -> Kollection<T> { | |
get { | |
precondition(!indices.contains { !self.indices.contains($0) }) | |
return Kollection(array: array, indices: indices) | |
} | |
set { | |
precondition(self.array.count == newValue.array.count) | |
precondition(!newValue.indices.contains { !self.indices.contains($0) }) | |
for i in newValue.indices { | |
self[i] = newValue[i] | |
} | |
} | |
} | |
subscript(indices: Int...) -> Kollection<T> { | |
get { | |
return self[indices: indices] | |
} | |
set { | |
self[indices: indices] = newValue | |
} | |
} | |
subscript(where f: (T)->Bool) -> Kollection { | |
get { | |
let indices = self.indices.filter { f(array[$0]) } | |
return self[indices: indices] | |
} | |
set { | |
let indices = self.indices.filter { f(array[$0]) } | |
self[indices: indices] = newValue | |
} | |
} | |
mutating func update(f: (inout T)->Void) { | |
for i in indices { | |
f(&array[i]) | |
} | |
} | |
} | |
let a = [0, 1, 2, 3, 4] | |
var k1 = Kollection(array: a, indices: [0, 1, 2, 3, 4]) | |
print(k1) // Kollection<Int>(array: [0, 1, 2, 3, 4], indices: [0, 1, 2, 3, 4]) | |
k1[indices: [0, 2, 4]].update { (a: inout Int) in a += 100 } | |
print(k1) // Kollection<Int>(array: [100, 1, 102, 3, 104], indices: [0, 1, 2, 3, 4]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment