mownier
mownier

Reputation: 1779

Best way to check a nil object

I am checking for nil object like this:

if let _ = object {
    // Nothing to do here.
} else {
    // There's something that must be done here.
}

I would like to remove the part let _ = object because there's nothing to execute inside it. Aside from using if object == nil, what is the best way using the optional checking to verify if a certain object is nil?

Upvotes: 1

Views: 823

Answers (2)

Martin R
Martin R

Reputation: 539685

If your only intention is to check if the object is nil, and the unwrapped value is never needed, then a simple comparison with nil is the simplest way:

if object == nil {
    print("Warning: object is nil")
}

If you want to emphasize that this check is a precondition and you want to leave the current scope if the condition is not satisfied, then you can use a guard statement. But there is no need to unwrap the object to the unused variable:

guard object != nil else {
    print("Warning: object is nil")
    return
}

Upvotes: 4

Midhun MP
Midhun MP

Reputation: 107121

You can use guard statement for this purpose

guard let _ = object else {
    // Do something
    return
}

Upvotes: 2

Related Questions