import Foundation
public func sine <T: FloatingPoint > (_ x: T ) -> T{
return sin(x)
}
// Error: Cannot invoke 'sin' with an argument list of type '(T)'
有沒有辦法解決這個問題? 非常感謝。如何在Swift 3中使用帶浮點值的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)'
有沒有辦法解決這個問題? 非常感謝。如何在Swift 3中使用帶浮點值的sin(_:)
你可以說,也接受浮點類型如下贖罪方法:
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
}
}
另一種選擇是添加一個方法或計算的屬性擴展到浮點類型如下:
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
}
}
}
@LeoDabus謝謝你的建議。真的很感激它! –
可能重複[使Swift泛型玩重載函數](http://stackoverflow.com/questions/37369649/making-swift-generics-play-with-overloaded-functions)(答案是Swift 2,但我不要相信Swift 3中的任何內容都會改變,從而可以更容易地實現通用的'sin(_ :)'函數) – Hamish