简体   繁体   English

我们可以为返回可选值的swift函数添加@objc吗?

[英]Can we add @objc for swift function that returns optional value?

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. 我想将其公开给Objective-C运行时,所以在它之前添加@objc。

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 我不确定为什么不允许可选值,因为Apple在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. 您可以访问标有@objc属性的类或协议中的任何内容,只要它们与Objective-C兼容即可。 This excludes Swift-only features such as those listed here: 这不包括仅Swift的功能,例如此处列出的功能:

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

Int is a structure defined in Swift which listed in Swift-only features Int是Swift中定义的结构,仅在Swift功能中列出

https://developer.apple.com/library/prerelease/ios/documentation/Swift/Reference/Swift_Int_Structure/index.html#//apple_ref/swift/struct/s:Si 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 您需要将其分为两个功能或其他一些功能

An Objective-C function can't return a pointer to an Int. Objective-C函数无法返回指向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 然后在Objective-C中,您可以测试NSNotFound

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM