Skip to content

/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

swift
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

swift
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

SituationUse
A sensible default existsvalue ?? default
The rest of the function needs the valueguard let value else { return }
Only one block needs itif let value { ... }
A nil result is finevalue?.member
nil is impossible by constructionvalue! (crashes if you are wrong)

Sources