SafeExpression is a small Swift package that safely wraps NSExpression(format:)
, protecting your app from crashes caused by malformed expressions. If parsing fails, the wrapper throws a Swift Error
instead of crashing.
Apple's NSExpression(format:)
can crash your app if you pass an invalid format string. SafeExpression
prevents that by catching Objective-C exceptions and converting them into Swift throws
.
- Safe parsing of format strings
- Throws descriptive errors instead of crashing
- Usable in 100% Swift projects (no need for bridging headers)
Add the following to your Package.swift
:
.package(url: "https://github.com/dimkah/SafeExpression.git", from: "1.0.0")
- Open your project in Xcode.
- Go to
File
>Swift Packages
>Add Package Dependency
. - Enter the URL:
https://github.com/dimkah/SafeExpression.git
. - Choose the version you want to use (e.g.,
1.0.0
).
import SafeExpression
do {
let expression = try SafeExpressionWrapper.expression(format: "(5 + 2 * 3") // Invalid format (missing closing parenthesis)
let result = expression.expressionValue(with: nil, context: nil)
print("Result:", result ?? "nil") // Will not be reached since the expression is invalid
} catch {
print("Expression error:", error.localizedDescription) // Handle the error
// Output: Expression error: Invalid expression format
// or similar error message
// depending on the specific issue with the format string.
}
let expression = NSExpression(format: "5 + (2 *") // 💥 Crash!
do {
let expression = try SafeExpressionWrapper.expression(format: "5 + (2 *")
} catch {
print("Invalid expression:", error.localizedDescription)
}
✅ No crash — just a regular Swift error.
This project is licensed under the MIT License. See the LICENSE file for details.
Contributions are welcome! Please feel free to submit a pull request or open an issue if you find a bug or have a feature request.