Search code examples
swiftdarwin

In Swift (Darwin), why does exit() take an Int32 instead of a UInt8?


This complete Swift program gives an exit code of 255:

import Darwin
exit(-1)

When run from within Xcode I get Program ended with exit code: 255; or when compiled and run on the command line echo $? produces 255; etc. At some point Int32(-1) is being truncated and interpreted as an unsigned 8-bit integer.

I don't know where this conversion happens (perhaps in Darwin somewhere or when the value is passed into the host shell or OS?), but since exit() is a Darwin library function (not a Swift language feature), which is already specific to the platform, why is it defined to take an Int32 instead of a UInt8?


Solution

  • Because it's the standard C exit function, which has the following prototype:

    void exit(int);
    

    On your system that int is 32 bits so that's why Swift uses Int32 for it.

    The truncation happens somewhere inside the C exit function.