lukas_o
lukas_o

Reputation: 4236

swift using guard and typechecking in one line

I like using guard and came across the situation where I want to use where for a typecheck as well:

guard let status = dictionary.objectForKey("status") as! String! where status is String else { ...}

xCode complains correctly that it's always true.

My goal is to have an unwrapped String after the guard in one line.

How can I do this?

Upvotes: 0

Views: 998

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

When you use as! String! you tell Swift that you know that the object inside your dictionary must be a String. If at runtime the object is not a String, you let Swift throw a cast exception. That is why the where part of your check is not going to fail: either the status is going to be a String, or you would hit an exception prior to the where clause.

You can do an optional cast instead by using as? operator instead of as!. Coupled with guard let, this approach produces

guard let status = dictionary.objectForKey("status") as? String else { ... }
... // If you reached this point, status is of type String, not String?

Upvotes: 2

Yury
Yury

Reputation: 6114

Probably you want this?

guard let status = dictionary["status"] as? String else {
    // status does not exist or is not a String
}

// status is a non-optional String

Upvotes: 7

Related Questions