问题描述
我试图弄清楚如何为泛型类实现一个类型约束(在Swift中),它将泛型类型限制为数字类型。例如Double,Int等,但不是字符串。感谢您的帮助。您可以为泛型类指定类型约束(同时使用类和协议)(相同的语法适用使用尖括号:
class Foo< T:Equatable,U:Comparable> {}
要指定单个类型的多个需求,请使用其中
子句:
class Foo< T:UIViewController其中T:UITableViewDataSource,T:UITextFieldDelegate> {}
然而,您看起来并不像在泛型参数子句中指定可选需求,所以一个可能的解决方案是创建一个协议,所有的数字类型通过扩展实现,然后根据该要求限制你的类:
协议数字{}
扩展名Float:数字{}
扩展名Double:数字{}
扩展名Int:数字{}
class NumberCruncher< C1:Numeric> {
func echo(num:C1) - > C1 {
return num
}
}
NumberCruncher< Int>()。echo(42)
NumberCruncher< Float>()。echo 3.14)
I'm trying to figure out how to implement a type constraint for a generic class (in Swift) that will limit the generic types to numeric types only. For instance Double, Int, etc., but not string. Thanks for any help.
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)
这篇关于仅用于数字类型的泛型类型约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!