2016-08-16 54 views
8

代碼先前在雨燕2.2的工作現在拋出下面的錯誤在斯威夫特3:「字節」是不可用:使用withUnsafeBytes代替

enter image description here

這裏是我的代碼:

let tempData: NSMutableData = NSMutableData(length: 26)! 
tempData.replaceBytes(in: NSMakeRange(0, data.count), withBytes:data.bytes) 

我應該如何替換「data.bytes」以修復錯誤?我已經嘗試過實施'withUnsafeBytes'並查看了Apple的文檔,但無法擺脫它的困擾!

+0

你還沒有提供'data'的來源,但是如果你可以把它轉換成'Data',這將會更加簡單,你不需要在'NSMutableData'和'Data'之間進行橋接。你只需使用'replaceSubrange'。 –

回答

9

假設data具有類型Data,以下應工作:

let tempData: NSMutableData = NSMutableData(length: 26)! 
data.withUnsafeBytes { 
    tempData.replaceBytes(in: NSMakeRange(0, data.count), withBytes: $0) 
} 

使用的Data

/// Access the bytes in the data. 
/// 
/// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure. 
public func withUnsafeBytes<ResultType, ContentType>(_ body: @noescape (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType 

方法。封閉內部$0UnsafePointer<Void> 到字節(Xcode 8 beta 6中的UnsafeRawPointer)。

+0

你能更新答案爲swift 3.0 –

+0

@TejasArdeshna:*是* Swift 3. –

+0

爲什麼長度硬編碼爲26?它會對大數據造成什麼問題嗎?我是ios的新手,只是確認。 –