This question already has answers here:
Making Swift generics play with overloaded functions

(2个答案)


2年前关闭。



 import Foundation
 public func sine <T: FloatingPoint   > (_ x: T  ) -> T{
    return sin(x)
 }
 // Error: Cannot invoke 'sin' with an argument list of type '(T)'

有没有解决的办法?
非常感谢。

最佳答案

您可以使sin方法也接受FloatingPoint类型,如下所示:

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

另一种选择是向FloatingPoint类型添加方法或计算属性扩展,如下所示:
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
        }
    }
}

关于generics - 如何在Swift 3中将sin(_:)与FloatingPoint值一起使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39283419/

10-11 18:02