Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic type constraint for numerical type only

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.

like image 675
nalyd88 Avatar asked Jun 06 '14 02:06

nalyd88


People also ask

What are generic type constraints?

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.

Can generic classes be constrained?

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.

Which of the following generic constraints restricts the generic type parameter to an object of the class?

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.

How do you find the type of generic type?

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.


2 Answers

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) 
like image 60
Martin Gordon Avatar answered Oct 14 '22 17:10

Martin Gordon


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.

like image 38
DeFrenZ Avatar answered Oct 14 '22 15:10

DeFrenZ