问题
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