0

Why can't I use an Objective-C NSArray from Swift? According to the documentation: Working with Cocoa Data Types Swift should be bridging an NSArray<Type*>* to [Type].

I have this object defined in Objective-C:

@interface Data : NSObject
@property (strong, nonatomic, readonly) NSArray<NSNumber*>* arrayOfNumbers;
@end

This method defined in Objective-C:

@protocol DataReceiver
- (void)onDataReceived:(Data*)data;
@end

And this defined in Swift:

class MyDataReceiver : DataReceiver {
    func onDataReceived(data: Data!) {
        test(data.arrayOfNumbers[0]);
    }

    func test(num: Float) {
        NSLog("%f", num);
    }
}

And I'm getting the error: 'Type [NSNumber]! has no subscript members'. But this:

NSLog("%f", arrayOfNumbers[0]);

Compiles just fine....

What's happening here?

6
  • 1
    Does this work? NSLog("%@", data.arrayOfNumbers[0])
    – kennytm
    Jan 17, 2016 at 10:17
  • @kennytm Strange, it does compile with this approach, but doesn't work when I immediately try to pass it to a function like this: func test(num: Float) { NSLog("%f", num); } test(data.arrayOfNumbers[0]) (Gives the same error)
    – UnTraDe
    Jan 17, 2016 at 10:23
  • Do you really need Data as optional?
    – vadian
    Jan 17, 2016 at 10:36
  • @vadian Not at all, that's just what Swift generated.
    – UnTraDe
    Jan 17, 2016 at 10:48
  • Note that NSLog("%f", arrayOfNumbers[0]) compiles because the (Swift) compiler does not check the types of the variable argument list. However, it will not produce the correct output because an object pointer is interpreted as a floating point number.
    – Martin R
    Jan 17, 2016 at 11:09

1 Answer 1

2

The error message does not make sense but it is caused by the fact that you are trying to pass NSNumber to a method accepting a Float. That means that the compiler is trying to find a subscript method that would return a Float but obviously it can't find it.

func test(num: NSNumber) {
    NSLog("%@", num);
}

Should fix the problem. Objective-C to Swift bridging works as expected.

1
  • That makes sense, I guess the error message was a bit unclear to me. Thanks!
    – UnTraDe
    Jan 17, 2016 at 11:20

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.