ios - 从 Objective-C 调用 Swift 扩展函数的语法

标签 ios objective-c swift extension-methods

我有一个同时使用 Objective-C 和 Swift 的项目。一切都正确连接,因此我通常可以毫无问题地调用类的扩展。然而,在这种情况下,我必须向扩展传递一个参数,并且对语法感到困惑。

这是 Swift 3 扩展

extension Double {
    /// Rounds the double to decimal places value
    func rounded(toPlaces places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return (self * divisor).rounded() / divisor
    }
}

在 Swift 中,您可以使用

调用它
let x = Double(0.123456789).rounded(toPlaces: 4)

以下内容在 Objective-C 中不起作用:我已经尝试过它,但无法获得正确的语法:

double test = 0.123456789;
double roundedtot = test.roundedToPlaces:2;

具体错误是

'Member reference base type 'double' is not a structure or union'

我收集到的是一个 c 错误,但由于你可以在 swift 中调用该函数,所以似乎应该有一种方法在 Objc-C 中调用它

最佳答案

您需要将 @objc 添加到扩展定义中才能从 Objective-C 调用它。

另外,值得注意的是,只有的扩展(不能用于结构或枚举)可以从 Objective-C 访问。

关于ios - 从 Objective-C 调用 Swift 扩展函数的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55478446/

相关文章:

php - Error Domain=NSCocoaErrorDomain Code=3840 "No value."比较两个值时。 PHP、JSON 和 Swift

ios - 委托(delegate)返回 nil 且未被调用

iphone - 如何在代码中更改 UIBarButtonItem 的样式

ios - 对具有自己的转换的 ViewController 的不平衡调用

ios - 添加我的第一个 pod

ios - UITableView willDisplayCell 方法的不当行为

ios - 我陷入了初始化 UIView 子类的困境

ios - 维护 NSMutableDictionary 元素的顺序

objective-c - 如何知道 UIImageView 中图像的大小

swift - 我无法将图像放入 Swift 5 中的 UIButton