2017-02-26 35 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") 
      } 
     } 
    } 
}