You could just use the special characters in string litterals. Considering that the ASCII control codes STX
and ETX
have no special escape character, you could use their unicode scalar values 0x02
and 0x03
.
Directly in the string literal
You can construct the string using a string literal, if needed with interpolation:
let message="\u{02}...\u{03}\u{02}xyz\u{03}"
You can cross-check printing the numeric value of each byte :
for c in message.utf8 {
print (c)
}
Concatenating the string
You can also define some string constants:
let STX="\u{02}"
let ETX="\u{03}"
And build the string by concatenating parts. In this example, field1
and field2
are string variables of arbitrary length that are transformed to exactly 3 character length:
let message2=STX+field1.padding(toLength: 3, withPad: " ", startingAt:0)+ETX+STX+field2.padding(toLength: 3, withPad: " ", startingAt:0)+ETX
print (message2)
for c in message2.unicodeScalars {
print (c, c.value)
}