你可以写一个包装了数组结构,并提供了一个[]
操作:
struct Vec4<T> {
private var array: [T]
init(_ x: T, _ y: T, _ z: T, _ w: T) {
array = [x, y, z, w]
}
subscript(index: Int) -> T {
get {
return array[index]
}
set {
array[index] = newValue
}
}
}
或者使其更高效:
struct Vec4<T> {
private var x, y, z, w: T
init(_ x: T, _ y: T, _ z: T, _ w: T) {
(self.x, self.y, self.z, self.w) = (x, y, z, w)
}
subscript(index: Int) -> T {
get {
switch index {
case 0: return x
case 1: return y
case 2: return z
case 3: return w
default: preconditionFailure("invalid Vec4 subscript index")
}
}
set {
switch index {
case 0: x = newValue
case 1: y = newValue
case 2: z = newValue
case 3: w = newValue
default: preconditionFailure("invalid Vec4 subscript index")
}
}
}
}
为什么不直接用X的结构体,Y, z,w成员? – emlai
@tuple_cat,因为最终我想要一个代表4 * 4 = 16元素数组的类型别名 –
(与问题无关,但请注意,您的C示例数组不是预先初始化的:它包含随机值。) – emlai