Make Swift Assume Degrees for Trigonometry Calculations

后端 未结 7 2434
抹茶落季
抹茶落季 2020-12-06 14:01

Is it possible to change a setting, property, etc in Swift for iOS so that it assumes degrees for trigonometry calculations rather than radians?

For example si

相关标签:
7条回答
  • 2020-12-06 14:36

    I'm not entirely sure why you'd want to overload the default global method, but if you must, you can provide an alternate method signature:

    func sin(#degrees: Double) -> Double { // Require a parameter name for method call
        let radians: Double = degrees * (M_PI / 180) // Convert to rad
        return sin(radians) // Return result of default method call with automatic conversion
    }
    
    sin(degrees: 90) // 1.0
    sin(degrees: 180) // 0.0
    

    However, this is really an odd way of doing it, and it would make more sense to explicitly define your own method (that's what they're for), in a similar way:

    func sinFromDegrees(degrees: Double) -> Double {
        let radians: Double = degrees * (M_PI / 180)
        return sin(radians)
    }
    
    sinFromDegrees(90) // 1.0
    sinFromDegrees(180) // 0.0
    
    0 讨论(0)
提交回复
热议问题