convert(void *)to(SInt16 *)to Swift

时间:2018-01-12 07:02:24

标签: objective-c swift

我正在尝试将以下内容从Objective-C转换为Swift:

let array = ['1', '2', '0', '3', '0', undefined, '0', undefined, '3', '', ''];

array = array
    .filter(Boolean) // get only truthy values
    .map(Number);    // convert all values to number
    
console.log(array);

我已经明白-(int)fillBuffer:(void *)buffer { SInt16* p = (SInt16 *)buffer; // ... p[33] = 0 } 映射到Swift中的(void *)类型。

但是,我错过了将其转换为可以采用下标操作的步骤。

到目前为止,我已经有了这个:

UnsafeMutableRawPointer?

寻求反馈和建议。提前谢谢!

1 个答案:

答案 0 :(得分:3)

将void指针强制转换为类型指针

SInt16* p = (SInt16 *)buffer;

在Swift中使用assumingMemoryBound()

完成
func fillBuffer(_ buffer: UnsafeMutableRawPointer) -> Int {
    let p = buffer.assumingMemoryBound(to: Int16.self)
    // ...
    p[33] = 0
    return 0
}

测试代码:

var i16Array = Array(repeating: Int16(99), count: 40)
print(i16Array[33]) // 99
_ = fillBuffer(&i16Array) // passes a pointer to the element storage to the function
print(i16Array[33]) // 0