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
}
}
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.
func someFunc(value:UInt8) -> (SomeType?,NSError?) {
switch value {
case 0x00:
return (SomeType.foo(),nil)
case 0x13:
return (SomeType.bar(),nil)
default:
return (nil,NSError("Something wrong")
}
}
This is how I would implement the error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With