Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }
}
like image 862
Travis Griggs Avatar asked Dec 04 '15 19:12

Travis Griggs


2 Answers

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.

like image 125
Martin R Avatar answered Nov 07 '22 20:11

Martin R


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.

like image 43
Shane11 Avatar answered Nov 07 '22 21:11

Shane11