---
title: "What is if case in Swift and how do you use it?"
description: "if case matches a single pattern, such as one enum case with associated values, without writing a full switch. Learn the syntax, guard case and where clauses."
url: "https://bugsee.com/answers/swift/if-case/"
---

# What is if case in Swift and how do you use it?

`if case` tests a value against one pattern and, if it matches, lets you bind parts of it: `if case .success(let user) = result { ... }`.

A `switch` must cover every case. When you only care about one, `if case` is shorter, and it can bind associated values.

```swift
enum Response {
    case success(User)
    case failure(Error)
    case loading
}

if case .success(let user) = response {
    print(user.name)
}

// Combine with a condition
if case .success(let user) = response, user.isActive { }

// Ranges and optionals work too
if case 200...299 = statusCode { }
if case let value? = optionalValue { }

// Exit early
guard case .success(let user) = response else { return }

// Loop over matching elements only
for case .success(let user) in responses { print(user.name) }
```

Note that the pattern is on the left and the value on the right, which is the opposite of a normal comparison. For simple enums without associated values, `==` is usually clearer.

## Related questions

- [How do you fix "Unexpectedly found nil while unwrapping an Optional value"?](https://bugsee.com/answers/swift/unexpectedly-found-nil-while-unwrapping-optional/)
