Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bottom Type in Swift

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?

like image 807
Daniel Shin Avatar asked Dec 08 '15 08:12

Daniel Shin


1 Answers

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!")
like image 99
Daniel Shin Avatar answered Nov 08 '22 04:11

Daniel Shin