1
votes

I have a swift method like:

public func xIndexAtPoint(point: CGPoint) -> Int?

I want to expose it to Objective-C runtime, so I add @objc before it.

Method cannot be marked @objc because its result type cannot be represented in Objective-C

I am not sure why optional value is not allowed, since Apple does not mention it in https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html

You’ll have access to anything within a class or protocol that’s marked with the @objc attribute as long as it’s compatible with Objective-C. This excludes Swift-only features such as those listed here:

Generics

Tuples

Enumerations defined in Swift

Structures defined in Swift

Top-level functions defined in Swift

Global variables defined in Swift

Typealiases defined in Swift

Swift-style variadics

Nested types

Curried functions
2
Have you tried with an optional NSNumber instead. Either that or have a non optional int and just return -1 if there was an error e.t.c. - Rob Sanders
I need it to return NSInteger in Objective-C runtime. - Wingzero
But NSInteger is not a class value, so it cannot be nil, as an optional could be. - Dániel Nagy
It does not matter whether you are returning class type or structure type, optional can be used with any type in swift - Tushar
Optional types can be used with Objective-C, the (nullable) keyword adds support for this. It is automatically unwrapped in objective c so that an optional that contains null in swift will just be nil/null in objective c - Rob Sanders

2 Answers

0
votes

Int is a structure defined in Swift which listed in Swift-only features

https://developer.apple.com/library/prerelease/ios/documentation/Swift/Reference/Swift_Int_Structure/index.html#//apple_ref/swift/struct/s:Si

So the answer is No

you need to break it into two function or some other workaroud

0
votes

An Objective-C function can't return a pointer to an Int. You will need to create a wrapper function like:

@objc(xIndexAtPoint:)
public func _xIndexAtPoint(point: CGPoint) -> Int {
    return xIndexAtPoint(point: point) ?? NSNotFound
}

Then in Objective-C, you can test for NSNotFound

NSInteger i = [foo xIndexAtPoint:CGPointMake(10, 10)];
if(i == NSNotFound) {
}