Search code examples
swifttypecheckingtype-systems

Why does Swift's typechecking system allow a function that returns a type to not return anything?


Why does the following code works?

func square(_ x: Int) -> Int {
  fatalError()
}

fatalError() never returns anything (or rather it returns Never). Why would the type system not catch an issue here that the func does not return an Int even though it says it would?


Solution

  • Because fatalError returns Never. From the documentation, Never is,

    The return type of functions that do not return normally, that is, a type with no values.

    Through compiler magic, Swift understands that fatalError "does not return normally", namely that it crashes the app. This is why it does not complain about square not returning an Int.

    If a path of your function call a function that "does not return normally", that path does not return normally either. "Does not return normally" means that the caller won't be able to use the return value, so there is no point in enforcing the "you must return a value" rule in that path of your function.