Swift(4)中的简单结构初始化?

时间:2017-10-12 16:38:21

标签: arrays swift struct initialization

我是Swift的新手并试图移植一些代码。我从一个旧项目得到这个:

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 个答案:

答案 0 :(得分:2)

在Swift中,您可以使用Structs定义对象并创建一个接收初始化所需参数的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])]
相关问题