我正在试图弄清楚如何在Swift 3中使用Data中的指针。我在OBJ-C中使用以下简单方法修改10值文件中的第4个值。我如何在Swift 3中实现这一目标?
- (void) modifyFourthValueInFile:(NSString*)filePath {
//filePath is a file that contains 10 SInt16 values
NSData *data = [NSData dataWithContentsOfFile:filePath];
SInt16 *ourPointer = (SInt16*)data.bytes;
ourPointer += 3; // get the 4th value
*ourPointer = 1234; // modify the 4th value
[data writeToFile:filePath atomically:YES];
}
答案 0 :(得分:1)
可能的方法:
Data
值。withUnsafeMutableBytes()
改变字节。UnsafeMutableBufferPointer
,这允许修改
数据通过下标而不是指针算法。示例:
func modifyFile(filePath: String) {
let fileURL = URL(fileURLWithPath: filePath)
do {
var data = try Data(contentsOf: fileURL)
data.withUnsafeMutableBytes { (i16ptr: UnsafeMutablePointer<Int16>) in
let i16buffer = UnsafeMutableBufferPointer(start: i16ptr, count: data.count/MemoryLayout<Int16>.stride)
i16buffer[3] = 1234 // modify the 4th value
}
try data.write(to: fileURL, options: .atomic)
} catch let error {
print(error.localizedDescription)
}
}