Update - there is no difference between Optional and optional types in Swift - they are the same thing.
So in Swift they introduced the Type?
construct, that creates an optional type which "forces" the programmer to check if the value actually exists.
Also, in Swift there is no exception handling. But there is this built-in optionality mechanism.
This optional feature ?
is just an Optional<T>
enum behind the scenes inspired from Haskell's Maybe
.
I was wondering if there was any way of passing error information through the optional type.
Can "abc123".toInt()
return error information through the optional type Int?
? Could this replace Exceptions or NSError? Of course Cocoa still uses (and will use?) the NSError pattern.
Playing in the playground, I found this piece of code in the Swift "header":
protocol Printable {
var description: String { get }
}
extension T? : Printable {
var description: String { get }
}
Basically this adds a readonly property description
to ANY optional type. This would be super powerful (and could lead to many problems, I guess).
But after trying to extend myself the T?
I get an error:
Non-nominal type 'T?' cannot be extended
So why didn't they add a property to all optional types to carry with them error information? Wouldn't it be useful? I mean, you could return a tuple if you want multiple return types...
this is already part of the language
Optionals basically allow you to check whether or not a variable is nil. It's not meant to have an error message. For example take this Objective-C snippet:
In swift you would do something like this:
The apple docs say:
Per this answer, the correct syntax is:
Optional<T>
is the definition of Optionals (see below).Type?
is just the syntactic sugar for creating the type.From the Swift Programming Language iBook, the two declarations below are equivalent
Option
in swift is likeOption
in Scala (Maybe
in Haskell): It represents a value that may be absent.What you're looking for is something like the
Try
or theEither
monads from Scala, which represent two possible states of a computation, typically aSuccess
or aFailure
.This would be a different algebraic data type, beyond the purpose of an optional value.
Ultimately, since swift doesn't have full-fledged monads in the standard library, I think the default error handling pattern will stay the classic Cocoa
NSError
one.