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...