Prepitch: Character integer literals

Thanks @taylorswift for the proposal and thanks @johnno1962 for the insightful summary.

Being able to write let i: UInt8 = 'a' would be a game changer for people working a lot with embedded devices and serial/bluetooth/ble communication.

We basically just send & receive bytes and sometimes it makes a lof of sense to use the ASCII representation to make the code clearer.

One super simple example using Arduino. Imagine you have the following code running on your board:

  while (Serial.available() > 0) {
    
    uint8_t c = Serial.read();

    if (c == '+') {
      digitalWrite(LED_BUILTIN, HIGH);
    }
    else if (c == '-') {
      digitalWrite(LED_BUILTIN, LOW);
    }

    delay(250);
  
  }

Right now on the swift side, I need to write this to make the led blink:

let buffer: [UInt8] = [43, 45, 43, 45, 43, 45, 43, 45, 43, 45]
Darwin.write(fd, buffer, buffer.count)

It would be much clearer with:

let buffer: [UInt8] = ['+', '-', '+', '-', '+', '-', '+', '-', '+', '-', ]
Darwin.write(fd, buffer, buffer.count)

It's just an example but as things get more complex, it could really be helpful.

8 Likes