Shane D Shane D - 3 months ago 26x
Swift Question

Use Swift subscripts in objective-C

I have declared a subscript in swift and wanted to know if it is possible to use a swift subscript in objective-c ? Because I have made my class inherit from NSObject and made the subscript public. But I still cannot have access to it.
I am asking this question based on this line in the Apple's "Using Swift with Cocoa and Objective-C" :

enter image description here

How to make the subscript compatible to Objective-C or is Swift subscripts is a specific swift feature ?


It is absolutely possible, see:

class MyArray : NSObject {
    var data: [Int] = [0, 1, 2]

    subscript (index: Int) -> NSNumber {
        return data[index]


MyArray *array = [[MyArray alloc] init];
NSNumber *value = array[0];

There are some limitations though. You cannot return a primitive value (Int), you have to return an Obj-C object, e.g. NSNumber.