user678392
user678392

Reputation: 2031

How to create a generic class in Swift that accepts Doubles and Ints

I have a Point class. I would like to be able to work with Ints and Doubles, like the following:

var p1 = Point<Int>(dimensions:3)
var p2 = Point<Double>(dimension:3)

I thought something like the following might work:

  class Point<T> {
/* n dimensional point
 multiline comments ...
*/
let point : [T]
init(dimensions: Int, repeatedValue:T=0.0){
    self.point = Array(count: dimensions, repeatedValue: repeatedValue)

}

}

But it doesn't.

I then tried:

  class Point<T:FloatLiteralConvertible> {
/* n dimensional point
 multiline comments ...
*/
let point : [T]
init(dimensions: Int, repeatedValue:T=0.0){
    self.point = Array(count: dimensions, repeatedValue: repeatedValue)

}

}

But then I cannot create

 var p2 = Point<Int>(dimension:3)

I can't seem to figure out a way around this. Does Swift not let you do this?

Upvotes: 0

Views: 178

Answers (1)

Martin R
Martin R

Reputation: 539725

Int and Double both conform to IntegerLiteralConvertible, therefore you can define the class as

class Point<T:IntegerLiteralConvertible> {

    let point : [T]

    init(dimensions: Int, repeatedValue: T = 0){
        self.point = Array(count: dimensions, repeatedValue: repeatedValue)
    }
}

But note that if you want to do some arithmetic with the values, you will have to define a custom protocol which defines the required operations. See Swift generics: requiring addition and multiplication abilities of a type for an example how this can be done.

Upvotes: 1

Related Questions