Generic type constraint for numerical type only

generics, ios, swift

Solution

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)

Problem

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.

Original source