objc struct array to swift array

时间:2015-11-10 08:45:05

标签: objective-c swift

-(CGPoint*)func
{
    CGPoint* result = calloc(2, sizeof(CGPoint));
    result[0] = ..;
    result[1] = ..;

    return result;
}

如何将此数组转换为swift [CGPoint]?

1 个答案:

答案 0 :(得分:2)

您可以使用UnsafeBufferPointer按如下方式投射

    let pointer: UnsafeMutablePointer<CGPoint> = yourInstance.func()

    let swiftArray = Array(UnsafeBufferPointer(start: pointer, count: 2))

    free(pointer)

修改

如果确实需要使用C数组,您可能需要将func方法重写为:

- (CGPoint*)pointArray:(NSInteger *)length
{
    int arrSize = 2;
    CGPoint* result = calloc(arrSize, sizeof(CGPoint));
    result[0] = ...
    result[1] = ...

    *length = arrSize;

    return result;
}

然后在Swift方面:

    var arrayLength: Int = 0
    let pointer: UnsafeMutablePointer<CGPoint> = yourInstance.pointArray(&arrayLength)

    let swiftArray = Array(UnsafeBufferPointer(start: pointer, count: arrayLength))

    free(pointer)