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
)?
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.