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

橙三吉。 提交于 2019-12-13 06:57:32

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/28302650/how-to-create-a-generic-class-in-swift-that-accepts-doubles-and-ints

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!