Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
512 views
in Technique[技术] by (71.8m points)

ios - 'bytes' is unavailable: use withUnsafeBytes instead

Code that was previously working in Swift 2.2 is now throwing the following error in Swift 3:

enter image description here

Here is my code:

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

What should I replace "data.bytes" with to fix the error? I've tried implementing 'withUnsafeBytes' and had a look at Apple's documentation, but can't get my head around it!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming that data has type Data, the following should work:

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

using the

/// 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

method of Data. Inside the closure $0 is a UnsafePointer<Void> to the bytes (UnsafeRawPointer in Xcode 8 beta 6).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...