Travis Griggs Travis Griggs - 1 month ago 9
Swift Question

Swift generate error for default return value

The following code sample pretty well illustrates what I'm after. I have a function that is expected to return a given type. It does that based on an incomplete switch. But in the event the

default
case is reached, I was hoping to just generate an error. Rather than return an
optional
which someone chooses to
!
and then die at that point.

func someFunc(value:UInt8) -> SomeType {
switch value {
case 0x00:
return SomeType.foo()
case 0x13:
return SomeType.bar()
default:
break // BUT I WANT AN ERROR HERE
}
}

Answer

If you want the program to terminate in the default case (because the default case would indicate a programming error), use fatalError():

func someFunc(value:UInt8) -> SomeType {
    switch value {
    case 0x00:
        return SomeType.foo()
    case 0x13:
        return SomeType.bar()
    default:
        fatalError("Unexpected value \(value)")
    }
}

fatalError() causes the program to terminate immediately with a error message like

  fatal error: Unexpected value 99: file main.swift, line 13

The fatalError() function is marked with @noreturn (resp. with the return type Never in Swift 3), so the compiler won't complain on missing cases or missing return values.

In contrast to similar function like assert() or assertionFailure(), fatalError() is never "optimized away", it is evaluated in debug, optimized and unchecked builds.

Comments