I'm wondering if there is bottom type in the Swift language.
To weed out any confusion beforehand, unit type is a different kind than bottom type as we have it as Void
or ()
in swift. Also Any
is top type.
What I've found to be the closest, surprisingly, is @noreturn
attribute in the form of fatalError()
in that we can mostly pass this function to conform to most given arbitrary type.
But, of course, this is incomplete and thus a bad substitute for a true bottom type as, for example, Nothing
in Scala, undefined
in Haskell or even null
in Java.
So, is there a bottom type in Swift language?
Turns out there is no Bottom Type in swift, but we can mock its general behavior through few hacks with @noreturn
attribute and generics as explained in this talk.
func undefined<A>(_ message: String = "") -> A {
fatalError("Not Implemented: \(message)")
}
Then we can use it to mark yet-implemented parts of our code to pass compiler errors:
func someComplexFunction<U: User>(u: U) -> U {
return undefined("Do this after creating user")
}
Or to prove some invariances in our code:
let array = ["hello", "world"]
let hello: String = array.first ?? undefined("This is impossible!")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With