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
522 views
in Technique[技术] by (71.8m points)

ios - NSData from Byte array in Swift

I'm trying to create an NSData var from an array of bytes.

In Obj-C I might have done this:

NSData *endMarker = [[NSData alloc] initWithBytes:{ 0xFF, 0xD9 }, length: 2]

I can't figure out a working equivalent in Swift.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

NSData has an initializer that takes a bytes pointer: init(bytes: UnsafeMutablePointer <Void>, length: Int). An UnsafePointer parameter can accept a variety of different things, including a simple Swift array, so you can use pretty much the same syntax as in Objective-C. When you pass the array, you need to make sure you identify it as a UInt8 array or Swift's type inference will assume you mean to create an Int array.

var endMarker = NSData(bytes: [0xFF, 0xD9] as [UInt8], length: 2)

You can read more about unsafe pointer parameters in Apple's Interacting with C APIs documentation.


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

...