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
)?
Asked
Active
Viewed 3,786 times
2
-
Where's your code? What have you tried? You'll get more and better answers If you show what you've tried, and demonstrate that you’ve taken the time to try to help yourself. See [Ask] – Ashley Mills Mar 06 '17 at 17:39
2 Answers
9
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.

Martin R
- 529,903
- 94
- 1,240
- 1,382
-
This gives me `Initialization of 'UnsafeBufferPointer
' results in a dangling buffer pointer` – h345k34cr Jun 23 '20 at 09:18 -
@h345k34cr: Thanks for letting me know. I have added an updated version which should compile without problems. – Martin R Jun 23 '20 at 09:30
1
Better way to do it:
var data = Data()
let value: Int32 = 0x12345678
var bigEndianVal = value.bigEndian
withUnsafePointer(to: &bigEndianVal) {
data.append(UnsafeBufferPointer(start: $0, count: 1))
}

h345k34cr
- 3,310
- 5
- 21
- 28