2

I have a project with both objective-c and swift. Everything is hooked up properly so I can generally call extensions on classes without issue. In this case, however, I have to pass an argument to the extension and am getting hung up on the syntax.

Here is the Swift 3 Extension

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
    }
}

From Swift you can call it with

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

The following is not working in Objective-C: I have played around with it but can't get the correct syntax:

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

The specific error is

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

which I gather is a c error but since you can call the function in swift it seems there ought to be a way to call it in Objc-C

user1904273
  • 4,562
  • 11
  • 45
  • 96
  • 2
    What you're trying to do is not possible. `double` is a C-primitive type. It cannot have methods attached to it (that would violate C). – Rob Napier Apr 02 '19 at 18:44

1 Answers1

2

You need to add @objc to the extension definition in order to call it from Objective-C.

Also, it's important to note that only extensions for classes (not for structs or enums) are accessible from Objective-C.

Woodstock
  • 22,184
  • 15
  • 80
  • 118