Objective C const float *和Float tuple转换为Swift

时间:2016-04-13 15:21:01

标签: ios swift

昨晚,我把一些代码从ObjC移植到Swift,并且达到了我对Swift等效应该不熟悉的程度。

主要问题是如何在Swift中表示const float *。基于文档https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithCAPIs.html#//apple_ref/doc/uid/TP40014216-CH8-ID23我认为使用UnsafeMutablePointer<Float>听起来像是可接受的转换。

ObjC

- (void)renderWithModelViewProjectionMatrix:(const float *)model_view_matrix

夫特

func renderWithModelViewProjectionMatrix(modelViewMatrix: UnsafeMutablePointer<Float>)

但是在尝试传递modelViewMatrix参数时,我发现它被定义为Float元组m,如下所示

public struct _GLKMatrix4 {

    public var m: (Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float)
    public init(m: (Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float))
    public init()
}

将方法签名更改为

func renderWithModelViewProjectionMatrix(modelViewMatrix: (Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float)) 

(虽然凌乱)似乎解决了这个初始问题。

当试图在方法内部尝试使用该参数时,问题就变成了。

glUniformMatrix4fv(cubeMVPMatrix, 1, 0, modelViewMatrix)

导致错误Cannot convert value of type (Float, Float, Float...) to expected argument type UnsafePointer<Float>

以下是glUniformMatrix4fv方法签名供参考:

public func glUniformMatrix4fv(location: GLint, _ count: GLsizei, _ transpose: GLboolean, _ value: UnsafePointer<GLfloat>)

似乎在ObjC中,Float元组可以表示为const float *,但在Swift中它与UnsafePointer<Float>不兼容。

在传递Float元组的情况下,renderWithModelViewProjectionMatrix方法签名在Swift中应该是什么样的?如何调用glUniformMatrix4fv来预期传递UnsafeMutablePointer?

是否可以从(Float, Float, Float...)轻松转换为UnsafeMutablePointer<Float>

为了更好地了解ObjC的完整来源,我要转换来看看https://github.com/googlesamples/cardboard-ios/blob/master/CardboardSamples/TreasureHunt/TreasureHuntRenderer.m#L564

1 个答案:

答案 0 :(得分:1)

似乎从元组转换为数组可以修复编译错误。但不确定解决方案的正确性。

typealias Matrix4Type = (Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float, Float)

func arrayForTuple(tuple: Matrix4Type) -> [Float] {
    let reflection = Mirror(reflecting: tuple)
    var arr : [Float] = []
    reflection.children.forEach({ (label, value) in
        if let value = value as? Float {
            arr.append(value)
        }
    })
    return arr
}

然后在renderWithModelViewProjectionMatrix

let modelViewMatrix = arrayForTuple(modelViewMatrixTuple)
glUniformMatrix4fv(cubeMVPMatrix, 1, 0, modelViewMatrix)