简体   繁体   中英

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?

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!")

see Never

Basically, you can just do

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM