我正在尝试创建一个具有平均功能的通用 Queue 类,但是我在这样做时遇到了麻烦,因为我需要一个以某种方式表明 T(Int)
是有效操作的协议(protocol)。
这是我的尝试
class Queue<T:Numeric & Comparable> {
private var array:[T]
.....
func average() -> T {
return sum() / T(array.count)
}
}
然而,出于显而易见的原因,编译器说我不能这样做,因为 T 不支持显式初始化。实现此行为的协议(protocol)的名称是什么,或者我如何编写自己的代码?
最佳答案
请注意,Numeric
协议(protocol)还包括 FloatingPoint
类型,因此您应该将 Queue
通用类型限制为 BinaryInteger
.关于您的平均返回类型,您应该返回 Double
而不是通用整数。您的 Queue
类应该如下所示:
class Queue<T: BinaryInteger & Comparable> {
private var array: [T] = []
init(array: [T]) {
self.array = array
}
func sum() -> T {
return array.reduce(0, +)
}
func average() -> Double {
return array.isEmpty ? 0 : Double(Int(sum())) / Double(array.count)
}
// If you would like your average to return the generic type instead of Double you can use numericCast method which traps on overflow and converts a value when the destination type can be inferred from the context.
// func average() -> T {
// return sum() / numericCast(array.count)
// }
}
Playground 测试
let queue = Queue(array: [1,2,3,4,5])
queue.sum() // 15
queue.average() // 3
如果您想扩展Numeric
、BinaryInteger
或FloatingPoint
类型的数组,您可以查看此 answer .
关于swift - 整数转换为通用类型以计算平均值。非标称类型不支持显式初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48045516/