swift - 整数转换为通用类型以计算平均值。非标称类型不支持显式初始化

标签 swift

我正在尝试创建一个具有平均功能的通用 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

如果您想扩展NumericBinaryIntegerFloatingPoint 类型的数组,您可以查看此 answer .

关于swift - 整数转换为通用类型以计算平均值。非标称类型不支持显式初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48045516/

相关文章:

ios - Swift:是否可以从堆栈中删除 View Controller?

ios - 快速排序异常

ios - swift refreshcontrol,endRefreshing 不工作

ios - 停止 UIView 中的所有异步任务

ios - 如何知道一个字符串是否已经用特殊字符进行了特殊转义?

ios - 滚动表格时如何将inputView移动到键盘上方

swift - 如何在 NSURLSession 中使用 PUT 方法向 HTTPBody 添加数据?

json - Swift - 保存异步数据

ios - 为什么 GADBannerView 未声明?

ios - 验证失败时防止光标移动