Optional<Wrapped>) that holds either .some(Wrapped) or .none (nil). Use ? to declare it and unwrap safely with if let, guard let, or ?? instead of force-unwrapping with ! to avoid Unexpectedly found nil while unwrapping an Optional value crashes.Why this happens
Swift does not allow a normal variable to be missing. A String must contain a String, an Int must contain an Int. If you try var red: String = nil you get nil cannot be assigned to type 'String'. This strictness prevents a whole class of null-reference bugs, but it creates a problem: some values legitimately may not exist yet.
Think of a view controller that loads an avatar from cache or network, a dictionary lookup that may fail, or an NSError that only exists when something went wrong. You need a way to represent “a value or no value” without breaking the type system.
That is what an optional is. Despite the ? syntax, an optional String is not a String with a flag. It is a completely different type: Optional<String>. In the standard library it is defined as a generic enum:
enum Optional<Wrapped> {
case none
case some(Wrapped)
}
An optional is a container that holds either .none (which you see as nil) or .some with an associated value. Swift adds syntactic sugar so you can write String? instead of Optional<String>, compare to nil, and unwrap with ? and !, but underneath it is always that two-case enum.
How to fix it
The fix is to treat optionals as containers you must unwrap safely, not as normal values you can use directly.
1. Declare and check optionals correctly
Append ? directly to the type with no space. Any type can be optional, including your own structs and classes.
var name: String? = "Bertie"
var age: Int? = nil
class Person {}
var peter: Person? = Person()
class Car {
var modelName: String // must always have a value
var internalName: String? // may be missing
}
Only optionals can be nil. Checking against nil is just checking whether the enum is .none:
var name: String? = "Bob"
name = nil
if name != nil {
print("There is a name")
}
if name == nil {
print("Name has no value")
}
If you need a non-optional, you must provide a value at initialization and never assign nil to it.
2. Unwrap safely with if let and guard let
Never assume an optional contains a value. Unwrap it conditionally.
if let is best when you want to do something only if the value exists:
var name: String? = "Bob"
if let unwrappedName = name {
print("Hello, \(unwrappedName)")
} else {
print("No name to greet")
}
// Swift shorthand - same name
if let name = name {
print("Hello, \(name)")
}
guard let is best when you need the value to continue and want to exit early otherwise. This avoids nested pyramids:
func greet(name: String?) {
guard let name = name else {
print("No name provided")
return
}
// name is now a non-optional String for the rest of the function
print("Hello, \(name)")
}
Both forms safely handle .none without crashing. Avoid ! (force unwrap) unless you can prove the value cannot be nil at that point. Force unwrapping a nil triggers a runtime crash: Unexpectedly found nil while unwrapping an Optional value.
var maybeName: String? = nil
// print(maybeName!) // crash - do not do this
3. Replace force unwrap with nil coalescing and optional chaining
For defaults and chained calls, Swift provides safer sugar.
Use nil coalescing ?? to supply a default value when the optional is nil:
var nickname: String? = nil
let displayName = nickname ?? "Guest" // "Guest" if nickname is nil
print(displayName)
func isDefaultNumber(x: Int? = 5) -> Bool {
// x is Optional<Int> with a default of .some(5)
return x == 5
}
isDefaultNumber() // true - uses default 5
isDefaultNumber(x: nil) // false
isDefaultNumber(x: 10) // false
Use optional chaining ? to call properties, methods, or subscripts only if the optional has a value. The whole chain returns an optional:
class User {
var address: Address?
}
class Address {
var city: String = "Cupertino"
}
var user: User? = User()
let city = user?.address?.city // String? - nil if user or address is nil
print(city ?? "Unknown city")
If you need to handle an error that may or may not exist, model it as an optional instead of a dummy value:
var error: NSError? = nil
// later, if something fails:
// error = NSError(domain: "com.example", code: 1)
if let error = error {
print("Failed: \(error.localizedDescription)")
}
4. Handle optionals from APIs correctly
Many Apple APIs return optionals. Common examples are Int("123") which returns Int? because the string may not be numeric, dictionary["key"] which returns Value?, and UIImage(named:) which returns UIImage?.
Always unwrap the result instead of forcing it:
let text = "123"
if let number = Int(text) {
print(number + 1) // 124
}
let cache: [String: String] = ["title": "Hello"]
let title = cache["title"] ?? "Untitled"
let subtitle = cache["subtitle"] ?? "No subtitle"
If you are working with Interface Builder outlets, they are declared as implicitly unwrapped optionals (UILabel!) because they are nil during initialization but are expected to exist after the view loads. Do not create your own ! types to avoid unwrapping. Prefer ? and guard let.
How to prevent it
- Declare a variable as optional only when “no value” is a valid state. Otherwise use a non-optional and initialize it.
- Never use
!to silence the compiler. If you seeUnexpectedly found nil while unwrapping an Optional value, replace the force unwrap withif let,guard let, or??. - Prefer
guard letat the start of functions to unwrap required inputs and fail early. - Use
??for defaults and optional chaining?.for chained calls instead of manualnilchecks. - When bridging Objective-C, remember many imports are optional (
String?,NSError?). Check the generated Swift interface before force unwrapping. - Enable strict warnings: treat force unwraps in code review as a potential crash site.
FAQ
What is the difference between String and String??
String is guaranteed to contain a String value. String? is shorthand for Optional<String>, an enum that contains either .some(String) or .none. They are different types and cannot be assigned to each other without unwrapping.
Why does nil cannot be assigned to type 'String' appear?
Because only optionals can hold nil. nil is just Swift’s spelling for Optional.none. If a variable needs to be nil at any point, declare it as String?, Int?, or YourType?.
When is it okay to use !?
Almost never in your own code. Use ! only when the system guarantees a value exists after a certain point, like an @IBOutlet after viewDidLoad, or when you just checked != nil on the previous line. In all other cases, use safe unwrapping to avoid crashes.
Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.