2016-11-10 67 views
1

當試圖升級涉及文件導出到Swift 3的庫時,我遇到了兩個主要問題。我已閱讀apple/swift migration page,但仍不確定究竟是什麼纔是最好的方式確保我不會丟失任何這些字節。很多示例都是轉換字符串,但實際上我需要字節。Swift 3不安全的指針不明確的初始化和字節

我遇到的第一個問題是在下面的每一行中,以stream.write開頭,UnsafePointer<UIntX>(&var)返回一個錯誤,說Ambigious use of init

var xbuffer = [UInt8](repeating: 0, count: 2048 + 171*1024) 
let stream : OutputStream = OutputStream(toBuffer: &xbuffer, capacity: 2048 + 171*1024); 
stream.open(); 

//Version number (2 bytes) 
stream.write(Data(bytes: UnsafePointer<UInt8>(&(self.version)), count: 1).bytes.bindMemory(to: UInt8.self, capacity: Data(bytes: UnsafePointer<UInt8>(&(self.version)), count: 1).count),maxLength: 1); 

stream.write(Data(bytes: UnsafePointer<UInt8>(&(self.subVersion)), count: 1).bytes.bindMemory(to: UInt8.self, capacity: Data(bytes: UnsafePointer<UInt8>(&(self.subVersion)), count: 1).count),maxLength: 1); 

//Operation ID status code (2 bytes) 
var opId_big = CFSwapInt16HostToBig(self.operationId); 
stream.write(Data(bytes: UnsafePointer<UInt8>(&(opId_big)), count: 2).bytes.bindMemory(to: UInt8.self, capacity: Data(bytes: UnsafePointer<UInt8>(&(opId_big)), count: 2).count),maxLength: 2); 

//Request ID (4 bytes) 
requestId = requestId | 0x1; 
var rqid_big = CFSwapInt32HostToBig(requestId); 
stream.write(Data(bytes: UnsafePointer<UInt8>(&(rqid_big)), count: 4).bytes.bindMemory(to: UInt8.self, capacity: Data(bytes: UnsafePointer<UInt8>(&(rqid_big)), count: 4).count), maxLength: 4); 

我能夠通過創建Data時進行更改UnsafeRawPointerUnsafeBufferPointer改變這一點。

我這樣做後,我有另一個問題,其中Xcode將打印錯誤bytes is unavailable use withUnsafeBytes instead。所以總的來說,我可以使用類似的東西逐個修復小部分,但由於所有鏈接命令,我無法進行多個更改並嘗試使用stackoverflow解決方案和快速遷移實踐,因爲需要進行多個更改在鏈接的命令。

我很欣賞任何答案或啓示/方向。

Other Migration Page That Was Helpful

StackOverFlow Reference 1

回答

0

一般來說,你有沒有需要創建中間Data以字節序列寫入OutputStream

var xbuffer = [UInt8](repeating: 0, count: 2048 + 171*1024) 
    xbuffer.withUnsafeMutableBufferPointer{bufferPointer in 
     let stream : OutputStream = OutputStream(toBuffer: bufferPointer.baseAddress!, capacity: xbuffer.count); 
     stream.open(); 

     //Version number (2 bytes) 
     withUnsafeBytes(of: &self.version) { 
      stream.write($0.baseAddress!.assumingMemoryBound(to: UInt8.self), maxLength: 1) 
     } 

     withUnsafeBytes(of: &self.subVersion) { 
      stream.write($0.baseAddress!.assumingMemoryBound(to: UInt8.self), maxLength: 1) 
     } 

     //Operation ID status code (2 bytes) 
     var opId_big = self.operationId.bigEndian 
     withUnsafeBytes(of: &opId_big) { 
      stream.write($0.baseAddress!.assumingMemoryBound(to: UInt8.self), maxLength: 2) 
     } 

     //Request ID (4 bytes) 
     var rqid_big = (requestId | 0x1).bigEndian; 
     withUnsafeBytes(of: &rqid_big) { 
      stream.write($0.baseAddress!.assumingMemoryBound(to: UInt8.self), maxLength: 4) 
     } 
    } 
+0

今晚我會試試這個。感謝你的回答。我對swift很陌生,很久以前就在Objective-C中編寫了這個庫的核心。這將是超級有用的,如果它的工作! – napkinsterror