你可以寫一個包裝了數組結構,並提供了一個[]
操作:
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