问题
Both original answers to this questions are satisfactory but come to the solution in slightly different ways. I opted for the one that I found simpler to implement
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:
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;
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 } },
};
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]
but xcode tells me:
Cast from '[((Int, Int), (Int, Int, Int, Int))]' to unrelated type '[AAPLVertex]' always fails
and my app crashes on load.
回答1:
Try like this:
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))]
回答2:
This is how I would implement it:
import simd
struct Vertex {
var position: SIMD2<Float>
var color: SIMD4<Float>
}
extension Vertex {
init(x: Float, y: Float, r: Float, g: Float, b: Float, a: Float = 1.0) {
self.init(position: SIMD2(x, y), color: SIMD4(r, g, b, a))
}
}
let triangleVertices = [
Vertex(x: +250, y: -250, r: 1, g: 0, b: 1),
Vertex(x: -250, y: -250, r: 1, g: 1, b: 0),
Vertex(x: 0, y: -250, r: 0, g: 1, b: 1),
]
However, I'm not sure to what extent the Swift native SIMD types are compatible with Metal, as compared to the Objective C ones, though I suspect they're interoperable.
来源:https://stackoverflow.com/questions/56781233/swift-casting-int-tuples-to-custom-type-containing-float-vectors