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のFloatingPoint値でsin(_:)を使用する方法3
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のFloatingPoint値でsin(_:)を使用する方法3
あなたは次のようにも浮動小数点型でも受け入れる罪方法することができます:別のオプションは、次のように浮動小数点型にメソッドまたは計算されたプロパティー拡張を追加して
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-overload-functions)(答えはSwift 2ですが、私はSwift 3で何かが変わったとは思わないでください。これは一般的な 'sin(_ :)'関数の実装を容易にします – Hamish