If the file is present the Optional result will be the first 100 bytes of the file.
If the file is not present the Optional Excuse will be IoError.FILE_NOT_FOUND.
Try running this code below with and without a file called file_to_open.txt in the same directory.
Return a default value if Optional is empty
The ?? operator allows us to return a default value if the Optional is empty.
Modifying the returned Excuse
A common use of ?? is to catch an empty Optional and change
the Excuse to another more specific Excuse, which
allows us to distinguish one failure from the other,
even when they had the same Excuse originally.
Force unwrapping expressions
The force unwrap operator !! will
make the program panic and exit if the expression is an empty optional.
This is useful when the error should – in normal cases – not happen
and you don’t want to write any error handling for it.
That said, it should be used with great caution in production code.
Find empty Optional without reading the Excuse
Find empty Optional and switch on Excuse
if (catch) can also immediately switch on the Excuse value:
Which is shorthand for:
Run code if the Optional has a result
This is a convenience method, the logical inverse of
if (catch)
and is helpful when you don’t care about the empty branch of
the code or you wish to perform an early return.
Another example:
It is possible to add conditions to an if (try) but they must be
joined with &&. However you cannot use logical OR (||) conditions:
Shorthands to work with Optionals
Getting the Excuse
Retrieving the Excuse with if (catch excuse = optional_value) {...}
is not the only way to get the Excuse from an Optional, we can use the macro @catch instead.
Unlike if (catch) this will never cause automatic unwrapping.
Checking if an Optional has a result without unwrapping
The @ok macro will return true if an Optional result is present and
false if the Optional is empty.
Functionally this is equivalent to !@catch, meaning no Excuse was found, for example:
No void! variables
The void! type has no possible representation as a variable, and may
only be a function return type.
To store the Excuse returned from a void! function without
if (catch foo = optional_value),
use the @catch macro to convert the Optional to an anyfault: