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.
C# allows you to use constraints to restrict client code to specify certain types while instantiating generic types. It will give a compile-time error if you try to instantiate a generic type using a type that is not allowed by the specified constraints.
You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter. The code below constrains a class to an interface.
Value type constraint If we declare the generic class using the following code then we will get a compile-time error if we try to substitute a reference type for the type parameter.
Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.
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)
Strideable
is the smallest standard protocol that every standard number type conforms to, but it also has a few more types conforming to it. http://swiftdoc.org/protocol/Strideable/hierarchy/
Or you can use IntegerType
and FloatingPointType
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With