Bottom Type in Swift

598 views Asked by At

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?

2

There are 2 answers

1
Daniel Shin On

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!")
1
Patrick Beninga On

see Never

Basically, you can just do

func foo() -> Never {
    // you can't return
}