问题
import Foundation
public func sine <T: FloatingPoint > (_ x: T ) -> T{
return sin(x)
}
// Error: Cannot invoke 'sin' with an argument list of type '(T)'
Is there a way around this? Many thanks.
回答1:
You can make a sin method that accepts FloatingPoint type also as follow:
import UIKit
func sin<T: FloatingPoint>(_ x: T) -> T {
switch x {
case let x as Double:
return sin(x) as? T ?? 0
case let x as CGFloat:
return sin(x) as? T ?? 0
case let x as Float:
return sin(x) as? T ?? 0
default:
return 0 as T
}
}
Another option is adding a method or a computed property extension to FloatingPoint type as follow:
extension FloatingPoint {
var sin: Self {
switch self {
case let x as Double:
return UIKit.sin(x) as? Self ?? 0
case let x as CGFloat:
return UIKit.sin(x) as? Self ?? 0
case let x as Float:
return UIKit.sin(x) as? Self ?? 0
default:
return 0 as Self
}
}
}
来源:https://stackoverflow.com/questions/39283419/how-to-use-sin-with-a-floatingpoint-value-in-swift-3