T应遵守哪种协议来传递此错误?
class func magnitude<T: BinaryFloatingPoint>(_ n: T) where T: CVarArg {
// …
let p = Int(log10(n))
// …
}
错误如下:
Cannot invoke 'log10' with an argument list of type '(T)'
答案 0 :(得分:0)
基于Martin R提示,我想出了以下内容(我添加了虚构的代码以便可以编译它),这很好用:
protocol FloatingPointMathType : BinaryFloatingPoint, CVarArg {
var _log10Value : Self { get }
}
extension Float: FloatingPointMathType {
var _log10Value : Float {return log10(self)}
}
extension Double: FloatingPointMathType {
var _log10Value : Double {return log10(self)}
}
extension CGFloat: FloatingPointMathType {
var _log10Value : CGFloat {return log10(self)}
}
func log10<T:FloatingPointMathType>(_ x:T) -> T {return x._log10Value}
class Format {
class func magnitude<T: BinaryFloatingPoint>(_ n: T) -> Int {
let p = Int(log10(n))
return p
}
}
let d: Double = 12.0
print(Format.magnitude(d))