Subscript

subscript(_:)

Subscript access, with an array of indexes, for the multidimensional array.

Declaration

subscript(key: [NSNumber]) -> NSNumber { get set }

Discussion

Using an array of indexes is the most convenient way to access the elements of the array, but it's also the least efficient. If the subscript is used in a loop, avoid creating a new array for each iteration.

Listing 1

Accessing an element in a three-dimensional array with an array of indexes.

var index: [NSNumber] = [i0, i1, i2]
let value = multiArray[index]

You'll get the best performance through direct access, using the indexes and strides to calculate the offset.

Listing 2

Calculating the offset and directly accessing the element at [i0, i1, i2].

let pointer = UnsafeMutablePointer<Double>(OpaquePointer(multiArray.dataPointer))
let offset = i0 * multiArray.strides[0].intValue + 
             i1 * multiArray.strides[1].intValue + 
             i2 * multiArray.strides[2].intValue
let value = pointer[offset]

See Also

Accessing Values

subscript(Int) -> NSNumber

Single, linear subscript access for the multidimensional array.

Beta Software

This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.

Learn more about using Apple's beta software