2017-10-12 6 views
-5

私はSwiftに慣れていて、いくつかのコードを移植しようとしています。私は古いプロジェクトからこれを持っています:Swift(4)での単純な構造の初期化?

typedef struct { 
    float Position[3]; 
    float Normal[3]; 
    float TexCoord[2]; // New 
} iconVertex; 

const iconVertex iconVertices[] = { 
    {{0.0,0.0, 0.0}, {0, 0, 1.0}, {0, 0}}, 
    {{1.0, 0.0, 0.0}, {0, 0, 1.0}, {1, 0}}, 
    {{0.0, 1.0, 0.0}, {0, 0, 1.0}, {0, 1}}, 
    {{1.0, 1.0, 0.0}, {0, 0, 1.0}, {1, 1}}, 
}; 

Swiftで同じ配列の初期化を行う方法はありますか? ありがとう!

答えて

1

Swiftでは、構造体を使用してオブジェクトを定義し、初期化する必要があるパラメータを受け取るinitメソッドを作成できます。

struct IconVertex { 
    var position: [Double] 
    var normal: [Double] 
    var textCoord: [Double] 

    init(position: [Double], normal: [Double], textCoord: [Double]) { 
     self.position = position 
     self.normal = normal 
     self.textCoord = textCoord 
    } 
} 

let iconVertices: [IconVertex] = [ 
IconVertex(position: [0.0,0.0, 0.0], normal: [0, 0, 1.0], textCoord: [0, 0]), 
IconVertex(position: [1.0, 0.0, 0.0], normal: [0, 0, 1.0], textCoord: [1, 0]), 
IconVertex(position: [0.0, 1.0, 0.0], normal: [0, 0, 1.0], textCoord: [0, 1]), 
IconVertex(position: [1.0, 1.0, 0.0], normal: [0, 0, 1.0], textCoord: [1, 1])] 
+5

'init'は必要ありません。 'struct'を使うと、他のものを提供していなければ自動的にそのような' init'を取得します。 – rmaddy

+0

良い点!しかし、いくつかのコードを移植しているので、 'init'を作成する方法を示すのも便利だと思いました – jvrmed

+0

おそらく、配列の代わりに' Vector3D'またはタプルを使いたいかもしれません。 –

関連する問題