Applying Generics to Variables and Functions - Swift

自古美人都是妖i 提交于 2019-12-25 03:14:29

问题


I'm trying to use generics in swift in order to initialise variables within my Vector3D class. However, upon assigning the protocol 'Number' to my variable (to make it either a Double or Float) I get the following error:

Protocol 'Number' can only be used as a generic constraint because it has Self or associated type requirements

public protocol Number {
    func +(l: Self, r: Self) -> Self
}    
extension Double : Number {}
extension Float  : Number {}


class Vector3D: NSObject {

    var xCord: Number
    var yCord: Number
    var zCord: Number


    func Vector3D(x: [Number], y: [Number], z: [Number]) {
        self.xCord = x
        self.yCord = y
        self.zCord = z
    }
}

My questions is then, how do you apply generics to variables in swift and in functions?


回答1:


You can't add generics to variables in Swift as already shown in this answer, but you can add generics to a function like that:

func swapTwoValues<T>(inout a:T, inout b:T){
  let temporaryA = a
  a = b
  b = temporaryA
}

Check the apple Documentation.




回答2:


The generic is created here <T>. It's like a variable for Types. You can change the T to anything you want as long as it's not used as a Type somewhere. The constraint bit is : Number. It constraints the type of T to the types that adhere to the Number Protocol.

func Vector3D<T: Number>(x: [T], y: [T], z: [T]) {
    self.xCord = x
    self.yCord = y
    self.zCord = z
}

As stated in the other answer, Variables and Constants cannot be of type Generic.



来源:https://stackoverflow.com/questions/28160345/applying-generics-to-variables-and-functions-swift

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