2

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 ?

0

1 Answer 1

4

It is absolutely possible, see:

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

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

Obj-C:

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I didn't know this, it surprises me that this works.
Super. I did not knew about the limitations. I was returning Any from my subscript. This works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.