如何在Swift 3中使用带有FloatingPoint值的sin(_:) [英] How to use sin(_ : ) with a FloatingPoint value in Swift 3
本文介绍了如何在Swift 3中使用带有FloatingPoint值的sin(_:)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import Foundation
public func sine< T:FloatingPoint> (_ x:T) - > T {
return sin(x)
}
//错误:无法用类型为'(T)'的参数列表调用'sin'
有没有办法解决这个问题?
非常感谢
解决方案
您可以创建一个接受FloatingPoint类型的sin方法,如下所示:
pre $
import UIKit
func sin< T:FloatingPoint>(_ x:T) - > T {
switch x {
case let x as double:
return sin(x)as? T? 0
的情况下让x作为CGFloat:
返回sin(x)as? T? 0
case让x为浮点数:
返回sin(x)as? T? 0
default:
return 0 as T
}
}
另一个选择是向FloatingPoint类型添加一个方法或一个计算的属性扩展如下:
扩展FloatingPoint {
var sin:self {
switch self {
case let x as Double:
return UIKit.sin(x)as?自我? 0
case让x为CGFloat:
返回UIKit.sin(x)as?自我? 0
大小写为x浮点数:
返回UIKit.sin(x)as?自我? 0
default:
return 0 as Self
}
}
}
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.
解决方案
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
}
}
}
这篇关于如何在Swift 3中使用带有FloatingPoint值的sin(_:)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文