How to use sin(_ : ) with a FloatingPoint value in

2019-05-10 02:37发布

This question already has an answer here:

 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条回答
对你真心纯属浪费
2楼-- · 2019-05-10 03:00

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
        }
    }
}
查看更多
登录 后发表回答