简体   繁体   English

如何使用泛型比较两种类型的大小

[英]How to use generics to compare the size of two types

I want to define a method to compare stuff such as int or double etc, using Generics.我想定义一个方法来比较诸如intdouble东西,使用泛型。 But I'm having this error:但我有这个错误:

Binary operator '>' cannot be applied to two 'T' operands.二元运算符“>”不能应用于两个“T”操作数。

Here's my code, how can I make it work?这是我的代码,我怎样才能让它工作?

func test<T:Numeric>(a: T,b:T)-> T{
    return a > b ? a : b
}

I have solved by:我已经解决了:

 func test<T:Comparable>(a: T, b: T)-> T {
    return a > b ? a : b
}

The > operator requires conformance to Comparable >运算符需要符合Comparable

func test<T : Comparable>(a: T, b: T) -> T {
    return a > b ? a : b
}

However the function already exists in the Swift Standard Library and is called max然而,该函数已经存在于 Swift 标准库中并被称为max

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM