Generics 如何在Swift 3中将sin(:)与浮点值一起使用 导入基础 公共函数正弦(x:T)->T{ 返回sin(x) } //错误:无法使用类型为“(T)”的参数列表调用“sin”
有办法解决这个问题吗?Generics 如何在Swift 3中将sin(:)与浮点值一起使用 导入基础 公共函数正弦(x:T)->T{ 返回sin(x) } //错误:无法使用类型为“(T)”的参数列表调用“sin”,generics,floating-point,swift3,Generics,Floating Point,Swift3,有办法解决这个问题吗? 非常感谢。您可以创建一个接受浮点类型的sin方法,如下所示: import Foundation public func sine <T: FloatingPoint > (_ x: T ) -> T{ return sin(x) } // Error: Cannot invoke 'sin' with an argument list of type '(T)' import UIKit func sin<T: Floa
非常感谢。您可以创建一个接受浮点类型的sin方法,如下所示:
import Foundation
public func sine <T: FloatingPoint > (_ x: T ) -> T{
return sin(x)
}
// Error: Cannot invoke 'sin' with an argument list of type '(T)'
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
}
}
@谢谢你的建议。真的很感激!非常感谢。Leo:)您可以通过使用条件类型转换模式删除第一组强制向下转换–
case let x as Double
等。这种切换和转换在运行时添加了大量分支。这可能会对性能产生非常严重的影响,这在像sin
这样的函数中可能非常重要,而这些函数实际上经常被调用。
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
}
}
}