将泛型应用于变量和函数-Swift [英] Applying Generics to Variables and Functions - Swift
问题描述
我试图快速使用泛型,以便在Vector3D类中初始化变量.但是,在将协议"Number"分配给我的变量(使其变为Double或Float)后,出现以下错误:
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:
协议"Number"只能用作通用约束,因为它 有自我或相关类型要求
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
}
}
那么,我的问题是,如何将泛型应用于swift和函数中的变量?
My questions is then, how do you apply generics to variables in swift and in functions?
推荐答案
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
}
这篇关于将泛型应用于变量和函数-Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!