How to use sin(_ : ) with a FloatingPoint value in Swift 3 [duplicate]

旧巷老猫 提交于 2019-12-22 10:23:01

问题


 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:


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
        }
    }
}


来源:https://stackoverflow.com/questions/39283419/how-to-use-sin-with-a-floatingpoint-value-in-swift-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!