繁体   English   中英

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

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

我有一个快速的方法,如:

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

我想将其公开给Objective-C运行时,所以在它之前添加@objc。

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

我不确定为什么不允许可选值,因为Apple在https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html中没有提及

您可以访问标有@objc属性的类或协议中的任何内容,只要它们与Objective-C兼容即可。 这不包括仅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是Swift中定义的结构,仅在Swift功能中列出

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

所以答案是否定的

您需要将其分为两个功能或其他一些功能

Objective-C函数无法返回指向Int的指针。 您将需要创建一个包装函数,例如:

@objc(xIndexAtPoint:)
public func _xIndexAtPoint(point: CGPoint) -> Int {
    return xIndexAtPoint(point: point) ?? 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