Skip to content

Instantly share code, notes, and snippets.

@dterekhov
Created October 20, 2025 12:36
Show Gist options
  • Select an option

  • Save dterekhov/5e26cfe6a8a04ae5e7b748b2ced61c3d to your computer and use it in GitHub Desktop.

Select an option

Save dterekhov/5e26cfe6a8a04ae5e7b748b2ced61c3d to your computer and use it in GitHub Desktop.
Typed throws #swift-api
// MARK: - Swift 6: Typed throws
// Define a specific error type for integer parsing.
enum IntegerParseError: Error {
case nonDigitCharacter(String, index: String.Index)
}
/// Parses a string into an integer, throwing a specific typed error if parsing fails.
///
/// - Parameter string: The string to parse.
/// - Throws: `IntegerParseError` only, making it a *typed throw*.
/// - Returns: The parsed integer value.
func parse(string: String) throws(IntegerParseError) -> Int {
for index in string.indices {
// Example logic: detect non-digit character and throw a typed error.
throw IntegerParseError.nonDigitCharacter(string, index: index)
}
return 0
}
// Example usage:
do {
try parse(string: "123a")
} catch let error as IntegerParseError {
print("Failed with: \(error)")
}
// This feature aligns Swift more closely with strong static typing principles — similar to typed exceptions in languages like Rust’s Result<T, E> or Swift’s own Result enum, but applied to throws functions directly.
@dterekhov
Copy link
Author

FDFD77D0-F12E-4572-84D4-F022064B4DDE_1_105_c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment