Swift:将 int 元组转换为包含浮点向量的自定义类型 [英] Swift: Casting int tuples to custom type containing float vectors

查看:77
本文介绍了Swift:将 int 元组转换为包含浮点向量的自定义类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对这个问题的两个原始答案都令人满意,但得出的解决方案略有不同.我选择了我认为更容易实现的一种

我正在尝试翻译一些 ObjectiveC,从此苹果金属文档/示例,然后将金属代码转换为 swift,但在这一点上遇到了一些麻烦:

I'm attempting to translate some ObjectiveC, from this apple metal doc/example, and metal code into swift but having some trouble with this bit:

这是我正在使用的 typedef,这是必要的,以便金属着色器可以计算我的顶点数据(来自 simd.h 的浮点向量很重要):

here is the typedef I'm using, which is necessary so that the metal shaders can computer my vertex data (the float vectors from simd.h are significant):

#include <simd/simd.h>

typedef struct
{
  vector_float2 position;
  vector_float4 color;
} AAPLVertex;

在目标 C 中,您可以这样做将一些数据转换为这种类型:

In the objective C you can just do this to cast some data to this type:

static const AAPLVertex triangleVertices[] =
{
    // 2D positions,    RGBA colors
    { {  250,  -250 }, { 1, 1, 1, 1 } },
    { { -250,  -250 }, { 1, 1, 0, 1 } },
    { {    0,   250 }, { 0, 1, 1, 1 } },
};

但是你如何在 Swift 中做到这一点呢?我已经尝试过:

But how do you do this in Swift? I've attempted this:

  private let triangleVertices = [
    ( (250,  -250), (1, 0, 1, 1) ),
    ( (-250,  -250), (1, 1, 0, 1) ),
    ( (0,  250), (0, 1, 1, 1) )
  ] as? [AAPLVertex]

但 xcode 告诉我:

but xcode tells me:

从 '[((Int, Int), (Int, Int, Int, Int))]' 转换为不相关的类型 '[AAPLVertex]' 总是失败

我的应用程序在加载时崩溃.

and my app crashes on load.

推荐答案

试试这个:

import simd

struct AAPLVertex {
    let position: float2
    let color: float4
}

let  triangleVertices: [AAPLVertex] = [
     // 2D positions,    RGBA colors
    .init(position: .init( 250, -250), color: .init(1, 0, 1, 1)),
    .init(position: .init(-250, -250), color: .init(1, 1, 0, 1)),
    .init(position: .init(   0, -250), color: .init(0, 1, 1, 1))]

这篇关于Swift:将 int 元组转换为包含浮点向量的自定义类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆