簡體   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