gpt4 book ai didi

Swift BinaryFloatingPoint 泛型在 log10() 调用上暴露编译错误

转载 作者:行者123 更新时间:2023-11-30 11:37:49 30 4
gpt4 key购买 nike

T 应该遵守什么协议(protocol)来传递这个错误?

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)'

最佳答案

根据 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))

关于Swift BinaryFloatingPoint 泛型在 log10() 调用上暴露编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49554768/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com