Search code examples
swiftfunctionmethodscallnaming

How can I call a global function inside a method / property variable with the same name?


For example, I have a property called ceil inside my class. Inside the function, I want to call the global function ceil. How can I do that?

class Example : BaseClass {
    var ceil : Double { return ceil(self); } // Error: Cannot call value of non-function type 'Double';
    func round : Double { return round(self); } // Infinite recursive
    var flooring : Double { return floor(self); } // Success
}

But if for example I don't want to use ceiling. I want to use ceil. How can I do that in this case? Is it possible? I'm thinking if I can call the global function such as Math.ceil(self) if it's possible.


Solution

  • You can use var ceil : Double { return Darwin.ceil(self) }

    You should use an extension for your use case, no need to create a new class. This way you can use the methods whenever you needed on a Double without instantiating a new class

    extension Double {
      var ceil : Double { return Darwin.ceil(self) }
      var floor : Double { return Darwin.floor(self) } // Success
    }