-
Notifications
You must be signed in to change notification settings - Fork 7
swift philosophy
Here we discuss some of the design philosophy behind Swift generally and behind some of the stricter design decisions in Swift for Arduino.
On Sentinel Values...
"...sentinel values is a term that Apple use when introducing some aspects of Swift’s design. That and “safe” vs “unsafe” behaviour are some of their guiding philosophies that they talk about. As I see it, a lot of it is sort of defined in opposition to how C and C++ work. Sentinel values are a concept that only really has meaning with APIs. If you imagine the classic C/unix APIs, think if you’re asking “what is the size of file X”, as a programmer, you write the code, then maybe something like “allocate a big enough buffer to handle the file”, and move on to the next code. Because you’re busy and you’ve got a project manager leaning over your shoulder you don’t have the luxury of time to stop, smoke a pipe and think, “now hang on here, what if something unexpected happens at this point?“. The problem is C and the C style APIs have no natural way to communicate “non golden path”. So what happens if the file is missing or you don’t have permission? Classic C APIs like fstat would return -1 for the file size, then you as a programmer would either not know, and would get a bug/crash, or you would have written a check for -1, then look at errno and see what’s wrong, plus handler code. This is about as good an API as you can write in C, a badly written API would return 0 because that’s indistinguishable from a genuinely empty file, although in some cases it’s an OK return as it’s not within the possible range of valid results, and benefits from the fact that C naturally tests against it as a boolean value. These are both sentinel values. Swift eschews these, in favour of either returning something like an enumeration, returning a nil/.none where it would have meaning or throwing an error in cases where no other option makes sense (like wrapping a C API that does this)."