2017-02-26 38 views
0

我希望能夠創建預先分配的特定大小的數組的變量。在C這可以這樣做:Swift仿真特定大小的C數組

typedef float vec16f[16]; 
vec4f myPresizedPreInitializedArray; 
myPresizedPreInitializedArray[2]=200.0f 

如何在Swift中做到這一點?

我曾嘗試以下:

  • typealias PositionVector = [Double]沒有大小限制,也不預初始化
  • class Vector4D: Array<Any> {}導致錯誤Inheritance from non-protocol, non-class type 'Array<Any>'
+0

爲什麼不直接用X的結構體,Y, z,w成員? – emlai

+0

@tuple_cat,因爲最終我想要一個代表4 * 4 = 16元素數組的類型別名 –

+0

(與問題無關,但請注意,您的C示例數組不是預先初始化的:它包含隨機值。) – emlai

回答

1

一種可能的方案是具有靜態成員的struct作爲模板

struct Template { 
    static let vec4 = [Float](repeatElement(10.0, count: 4)) 
} 

var newVec = Template.vec4 
newVec[2] = 200.0 

由於值類型語義,您總是獲得vec4的副本。

+0

我喜歡這個解決方案,但讓我們說我想從函數中返回newVec。返回類型是什麼? –

+0

它只是'[浮動]'。 – vadian

+0

反正我可以在函數聲明中強制類型?我想我必須這樣做'func multiplyMatrixAndMatrix(a:[Float],b:[Float]) - > [Float] {' –

0

你可以寫一個包裝了數組結構,並提供了一個[]操作:

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") 
      } 
     } 
    } 
}