You can specify type constraints (using both classes and protocols) for a generic class (same syntax applies to functions) using angle brackets:
class Foo<T: Equatable, U: Comparable> { }
To specify more than one requirement on a single type, use a where
clause:
class Foo<T: UIViewController where T: UITableViewDataSource, T: UITextFieldDelegate> { }
However, it doesn't look like you can specify optional requirements in a generic parameter clause, so one possible solution is to create a protocol that all the numeric types implement via extensions and then constrain your class on that requirement:
protocol Numeric { }
extension Float: Numeric {}
extension Double: Numeric {}
extension Int: Numeric {}
class NumberCruncher<C1: Numeric> {
func echo(num: C1)-> C1 {
return num
}
}
NumberCruncher<Int>().echo(42)
NumberCruncher<Float>().echo(3.14)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…