Does Swift provide conventional standard error classes/enums?

I could not find any standard error classes/enums in docs. For example, I have the following error situations:

  • Invalid null parameter
  • Parameter value out of range
  • Property value (of T!) not set
Answered by Claude31 in 763183022

There's not, AFAIK.

But you can easily define your error cases:

enum ErrorCode: Error {
    case nullValue(_ param: Int?, _ msg: String = "Invalid null parameter")
    case OutOfRange(_ param: Int, _ msg: String = "Parameter value out of range")
    case valueNotSet(_ t: T?, _ msg: String = "Property value (of T!) not set")
}
Accepted Answer

There's not, AFAIK.

But you can easily define your error cases:

enum ErrorCode: Error {
    case nullValue(_ param: Int?, _ msg: String = "Invalid null parameter")
    case OutOfRange(_ param: Int, _ msg: String = "Parameter value out of range")
    case valueNotSet(_ t: T?, _ msg: String = "Property value (of T!) not set")
}

Maybe reconsider why those specific error situations arise, and see if the Swift language can help avoid them. Do any of these apply? —

Invalid null parameter

If a method or function requires a parameter to be non-nil, then don’t declare it as optional.

Parameter value out of range

If this is for some sort of indexed collection, note how the same thing in Swift collections (like arrays) is a programmer error and thus causes a runtime error (crash).

Property value (of T!) not set

Not sure what this means, but again may be addressed by defining a property precisely as optional or non-optional. There are some well-defined use cases for implicitly unwrapped optionals, but otherwise they can get you into trouble.

If you’re thinking of an analog to Java’s unchecked exceptions, which represent programmer errors, then Swift’s equivalent generally is to crash the app. That’s a good thing.

Does Swift provide conventional standard error classes/enums?
 
 
Q