Home > Software engineering >  How can use round function without using SwiftUI library for helping Xcode for inferring?
How can use round function without using SwiftUI library for helping Xcode for inferring?

Time:08-25

I was playing around with an extension which I noticed Xcode does not know or it cannot infer round and I have to use like SwiftUI.round for helping Xcode! why it is the case? I think I do not have to use SwiftUI. because round function is a public function. So what happens there? and how can I use just round instead of SwiftUI.round?

Xcode Version 13.4.1 (13F100)

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello, world!")
            .onAppear {
                let value: Double = 2.69
                print(value.string)
            }
        
    }
}

extension Double {
    var string: String {
        let value: Self = SwiftUI.round(self*10.0)/10.0
        return String(describing: value)
    }
}

The issue is here that the round function is public as Xcode say:

public func round(_: Double) -> Double

So if I create a custom function called:

public func test(_ value: Double) -> String {
    return String(describing: value)
}

I would be able to call test function just with test(...) so why this is not possible with other public function called round(_: Double)

CodePudding user response:

Double has the method

mutating func round(_ rule: FloatingPointRoundingRule)

therefore, inside an extension of that type, round() without explicit module name is inferred as this mutating method. As an example, this would compile:

extension Double {
    var string: String {
        var x = self * 10.0
        x.round()
        let value = x/10.0
        return String(describing: value)
    }
}

You can use Darwin.round() or (apparently) SwiftUI.round() to refer explicitly to the C library function.

Alternatively, use the rounded() method.

  • Related