Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append Int to Data in Swift 3

Tags:

swift

datagram

I am writing datagram for sending it to a server via UDP socket. How can I append Int to the end of a datagram (already composed Data)?

like image 639
Alex Avatar asked Jan 31 '26 10:01

Alex


1 Answers

You can use the

public mutating func append<SourceType>(_ buffer: UnsafeBufferPointer<SourceType>)

method of Data. You probably also want to convert the value to network (big-endian) byte order when communicating between different platforms, and use fixed-size types like (U)Int16, (U)Int32, or (U)Int64.

Example:

var data = Data()

let value: Int32 = 0x12345678
var beValue = value.bigEndian
data.append(UnsafeBufferPointer(start: &beValue, count: 1))

print(data as NSData) // <12345678>

Update for Swift 4/5:

let value: Int32 = 0x12345678
withUnsafeBytes(of: value.bigEndian) { data.append(contentsOf: $0) }

The intermediate variable is no longer needed.

like image 194
Martin R Avatar answered Feb 03 '26 04:02

Martin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!