I first wrote about multiple-index arrays a year ago. Yesterday, someone was asking about them again so I updated my code for Swift 2.0
extension Array { typealias ArrayType = Element subscript(i1: Int, i2: Int, rest: Int...) -> [ArrayType] { get { var result : [Element] = [self[i1], self[i2]] for index in rest { result.append(self[index]) } return result } // Thanks Big O Note Taker set (values) { for (index, value) in zip([i1, i2] + rest, values) { self[index] = value } } } }
Not a huge change. Just really needed to tweak append and I added an explicit type for the result array. Update: Added the setter as suggested.
let foo = [1, 2, 3, 4, 5, 6, 7] println(foo[2]) // prints 3 println(foo[2, 4]) // prints [3, 5] println(foo[2, 4, 1]) // prints [3, 5, 2] println(foo[2, 4, 1, 5]) // prints [3, 5, 2, 6]
The setter runs out when the values do, so if you set alphabet[2, 3, 5] = ["X1", "X2"]
, only indices 2 and 3 get updated.
One Comment
How about a setter, as well?
set(vals) {
for (ind, val) in zip([i1, i2] + rest, vals) {
self[ind] = val
}
}