Created
October 20, 2025 12:36
-
-
Save dterekhov/5e26cfe6a8a04ae5e7b748b2ced61c3d to your computer and use it in GitHub Desktop.
Typed throws #swift-api
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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. |
Author
dterekhov
commented
Oct 20, 2025

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