/errors/swift/value-of-optional-type-must-be-unwrapped
Swift error: Value of optional type 'String?' must be unwrapped to a value of type 'String'
The commands on this page have not been executed by our verification runner yet.updated
- tool
- Swift
- exit code
- 1
- versions
- Swift 5.x – 6.x
- os
- macos, linux, windows
Value of optional type 'String?' must be unwrapped to a value of type 'String' is a Swift compile error: you used an Optional (a value that may be nil) where a non-optional value is required. Swift will not do this implicitly. Unwrap it with if let / guard let, give it a default with ??, or use optional chaining (?.). The compiler's fix-its offer the same choices: "Coalesce using '??'" or "Force-unwrap using '!'"; prefer the first.
Example
let env = ["PORT": "8080"]
let port: String = env["PORT"] // dictionary lookup returns String?
let number: Int = Int("42") // Int(String) is failable: Int?Each line gets the error with its own types, for example Value of optional type 'Int?' must be unwrapped to a value of type 'Int'.
Fixes
let env = ["PORT": "8080"]
let port = env["PORT"] ?? "3000" // default value
if let text = env["PORT"], let n = Int(text) { // optional binding
print("port", n)
}
func start(_ raw: String?) {
guard let raw, let n = Int(raw) else { // Swift 5.7+ shorthand for guard let raw = raw
print("invalid port"); return
}
print("starting on", n)
}
let length = env["HOST"]?.count // optional chaining: Int?Which tool to use
| Situation | Use |
|---|---|
| A sensible default exists | value ?? default |
| The rest of the function needs the value | guard let value else { return } |
| Only one block needs it | if let value { ... } |
| A nil result is fine | value?.member |
| nil is impossible by construction | value! (crashes if you are wrong) |
Sources
- docs.swift.orgdocs.swift.org/swift-book/documentation/the-swift-programming-language/thebasics/#Optionals
- docs.swift.orgdocs.swift.org/swift-book/documentation/the-swift-programming-language/thebasics/#Optional-Binding
- docs.swift.orgdocs.swift.org/swift-book/documentation/the-swift-programming-language/basicoperators/#Nil-Coalescing-Operator
Related pages
errors · swiftSwift Fatal error: Unexpectedly found nil while unwrapping an Optional valueSwift crashes with this fatal error when ! force-unwraps an Optional that is nil, or an outlet is not connected. Use if let, guard let or ?? to handle nil.errors · swiftSwift Fatal error: Index out of rangeSwift crashes with Index out of range when an array subscript is outside 0..<count: off-by-one loops or empty arrays. Use indices, first, last or bounds checks.errors · kotlinKotlin: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?Kotlin rejects a plain dot call on a nullable type like String?. Use ?. for a null result, ?: for a default, or check for null first so the value is smart-cast.